java发送邮件问题

来源:互联网 发布:python documentation 编辑:程序博客网 时间:2024/06/06 00:00
public class Dome2 {
@Test
public void fun() throws AddressException, MessagingException {
/*
* 1:得到session
*/
Properties pr = new Properties();
pr.setProperty("mail.host", "smtp.163.com");// 设置主机名
pr.setProperty("mail.smtp.auth", "true");// 设置是否认证


Authenticator a = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {


return new PasswordAuthentication("用户名", "客户端授权密码");
}
};
Session session = Session.getInstance(pr, a);
/*
* 2:创建MimeMessage
*/
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("发件人邮箱"));// 发件人
msg.setRecipients(RecipientType.TO, "邮箱1");// 设置收件人,to表示,发到收件人
// msg.setRecipients(RecipientType.CC, "邮箱2");//抄送
// msg.setRecipients(RecipientType.BCC, "邮箱3");//暗送
msg.setSubject("这是一封垃圾邮件");// 标题
msg.setContent("内容", "text/html;charset=utf-8");


/*
* 发送
*/
Transport.send(msg);

}


发送邮件,要注意3点:

1:导入activation.jar和mail.jar包

2:发送邮件的账号要开启smtp服务。

具体步骤如下:设置-pop3/smtp/imap然后点击开启即可

3:发送邮件的账号要设置客户端授权密码

具体步骤如下:设置-pop3/smtp/imap下面有一个管理客户端授权密码,然后点击,获取客户端授权密码。使用java发送邮件的时候用户名对应的密码就是这个密码。

0 0
原创粉丝点击