应用Authenticator类实现用户信息验证,结合Transport.send静态方法使用。
具体代码如下:
package javamail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* 使用其他方式创建邮件并发送
*/
public class Demo2 {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
//创建session
Properties props = new Properties();
//下面这两行是必须的,必须添加认证和协议
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
//设置主机名,不用设置端口,因为端口是默认的
props.setProperty("mail.host", "smtp.163.com");
//new SubAuthenticator("13432083020","abc123")
Session session = Session.getInstance(props,
//这里用到策略模式,用上面一行代码也可以
new Authenticator(){
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication
("13432083020@163.com","abc123");
}
}
);
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("********@163.com"));
msg.setSubject("中文主题");
//设置文本和文本类型
msg.setContent("<span style='color:red'>中文呵呵呵</span>"
, "text/html;charset=gbk");
//设置发送邮件的类型(直接发送/抄送/秘密发送)和收件人
msg.setRecipients(RecipientType.TO,
InternetAddress.parse(
"**********@163.com,*********@qq.com"));
Transport.send(msg);
}
}
参考书籍:《Java邮件开发详解》