这篇文章是要介绍如何要用JavaMail通过需认证的SMTP服务器发HTML格式的邮件。
首先在sun网站上下载JavaMail的实现,和JAF的实现(不知道为啥不放在一起),加入你的classpath。
代码先从Authenticator继承一个class,比如叫SMTPAuthenticator,这个要用于和SMTP服务器连接时做认证的。
class
SMTPAuthenticator
extends
Authenticator
{
private String user;
private String password;
public SMTPAuthenticator(String s, String s1) {
user = s;
password = s1;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}
private String user;
private String password;
public SMTPAuthenticator(String s, String s1) {
user = s;
password = s1;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
}
然后开始发邮件,
Session sendMailSession
=
null
;
SMTPTransport transport = null ;
Properties props = new Properties();
// 与服务器建立Session的参数设置
props.put( " mail.smtp.host " , " smtp.163.com " ); // 写上你的SMTP服务器。
props.put( " mail.smtp.auth " , " true " ); // 将这个参数设为true,让服务器进行认证。
SMTPAuthenticator auth = new SMTPAuthenticator( " user " , " mypassword " ); // 不用多说,用户名,密码。
sendMailSession = Session.getInstance(props, auth); // 建立连接。
// SMTPTransport用来发送邮件。
transport = (SMTPTransport) sendMailSession.getTransport( " smtp " );
transport.connect();
// 创建邮件。
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom( new InternetAddress( " me@163.com " ));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress( " somebody@gmail.com " ));
newMessage.setSubject( " This a test mail for Java Mail API);
newMessage.setSentDate( new Date());
// 使用MimeMultipart和MimeBodyPart才能发HTML格式邮件。
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(generateEmailBody(), " text/html;charset=gb2312 " ); // 发一个HTML格式的
Multipart mp = new MimeMultipart();
mp.addBodyPart(bodyPart);
newMessage.setContent(mp);
Transport.send(newMessage);
SMTPTransport transport = null ;
Properties props = new Properties();
// 与服务器建立Session的参数设置
props.put( " mail.smtp.host " , " smtp.163.com " ); // 写上你的SMTP服务器。
props.put( " mail.smtp.auth " , " true " ); // 将这个参数设为true,让服务器进行认证。
SMTPAuthenticator auth = new SMTPAuthenticator( " user " , " mypassword " ); // 不用多说,用户名,密码。
sendMailSession = Session.getInstance(props, auth); // 建立连接。
// SMTPTransport用来发送邮件。
transport = (SMTPTransport) sendMailSession.getTransport( " smtp " );
transport.connect();
// 创建邮件。
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom( new InternetAddress( " me@163.com " ));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress( " somebody@gmail.com " ));
newMessage.setSubject( " This a test mail for Java Mail API);
newMessage.setSentDate( new Date());
// 使用MimeMultipart和MimeBodyPart才能发HTML格式邮件。
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(generateEmailBody(), " text/html;charset=gb2312 " ); // 发一个HTML格式的
Multipart mp = new MimeMultipart();
mp.addBodyPart(bodyPart);
newMessage.setContent(mp);
Transport.send(newMessage);
OK,邮件发出去啦~~