用JavaMail发送HTML格式的邮件
java 代码
-
import java.security.Security;
-
import java.util.Date;
-
import java.util.HashMap;
-
import java.util.Map;
-
import java.util.Properties;
-
import javax.mail.Authenticator;
-
import javax.mail.Message;
-
import javax.mail.Multipart;
-
import javax.mail.PasswordAuthentication;
-
import javax.mail.Session;
-
import javax.mail.Transport;
-
import javax.mail.internet.InternetAddress;
-
import javax.mail.internet.MimeBodyPart;
-
import javax.mail.internet.MimeMessage;
-
import javax.mail.internet.MimeMultipart;
-
import org.apache.commons.logging.Log;
-
import org.apache.commons.logging.LogFactory;
-
import cn.soyu.util.MailClient;
-
import cn.soyu.shopping.view.orders;
-
/**
-
* 使用Gmail发送邮件
-
*
-
* @author Rain Chen
-
*/
-
public class GmailSender {
-
private static final Log logger = LogFactory.getLog(GmailSender.class);
-
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
-
private static final String USERNAME = "gdunser";//设定邮箱的用户名
-
private static final String PASSWORD = "123456";//设定邮箱的密码
-
private static final String TO_EMAIL = "gdunser@gmail.com";//设定收件人的信箱
-
private static final String SUBJECT = "你有新订单!";//设定邮件标题
-
private static final String FROM = "gdunser@gmail.com";//设定发件件的人
-
private static final String SMTP = "smtp.gmail.com";
-
public static void sender(String subject, String content) throws Exception {
-
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
-
// Get a Properties object
-
Properties props = System.getProperties();
-
props.setProperty("mail.smtp.host", SMTP);
-
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
-
props.setProperty("mail.smtp.socketFactory.fallback", "false");
-
props.setProperty("mail.smtp.port", "465");
-
props.setProperty("mail.smtp.socketFactory.port", "465");
-
props.put("mail.smtp.auth", "true");
-
Session session = Session.getDefaultInstance(props,
-
new Authenticator() {
-
protected PasswordAuthentication getPasswordAuthentication() {
-
return new PasswordAuthentication(USERNAME, PASSWORD);
-
}
-
});
-
Message msg = new MimeMessage(session);
-
InternetAddress[] address = null;
-
// 设定发邮件的人
-
msg.setFrom(new InternetAddress(FROM));
-
// 设定收信人的信箱
-
address = InternetAddress.parse(TO_EMAIL, false);
-
msg.setRecipients(Message.RecipientType.TO, address);
-
// 设定信中的主题
-
msg.setSubject(subject);
-
// 设定送信的时间
-
msg.setSentDate(new Date());
-
Multipart mp = new MimeMultipart();
-
MimeBodyPart mbp = new MimeBodyPart();
-
// 设定邮件内容的类型为 text/plain 或 text/html
-
mbp.setContent(content, "text/html;charset=GB2312");
-
mp.addBodyPart(mbp);
-
msg.setContent(mp);
-
Transport transport = session.getTransport("smtp");
-
transport.connect(SMTP, USERNAME, PASSWORD);
-
transport.sendMessage(msg, msg.getAllRecipients());
-
transport.close();
-
}
-
public static void main(String[] args) throws Exception {
-
sender(
-
SUBJECT,
-
"
恭喜你!收到邮件了!
www.3km.com.cn
"
);
-
System.out.println("Message sent.");
-
}
-
}