版权声明:本文为博主原创文章,未经博主允许不得转载☺ https://blog.csdn.net/u014571132/article/details/73028545
package com.sakura;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class sendEmailDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties prop = new Properties();
prop.put("mail.host", "smtp.163.com");
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.auth", "true");
try {
// 使用java发送邮件5步骤
// 1.创建sesssion
Session session = Session.getInstance(prop);
// 开启session的调试模式,可以查看当前邮件发送状态
session.setDebug(true);
Transport ts;
// 2.通过session获取Transport对象(发送邮件的核心API)
ts = session.getTransport();
// 3.通过邮件用户名密码链接
ts.connect("账户@163.com", "客户端授权码");
// 4.创建邮件
Message msg = createSimpleMail(session);
// 5.发送电子邮件
ts.sendMessage(msg, msg.getAllRecipients());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static MimeMessage createSimpleMail(Session session)
throws AddressException, MessagingException {
// 创建邮件对象
MimeMessage mm = new MimeMessage(session);
// 设置发件人
mm.setFrom(new InternetAddress("账户@163.com"));
// 设置收件人
mm.setRecipient(Message.RecipientType.TO, new InternetAddress(
"账户@163.com"));
// 设置抄送人
//mm.setRecipient(Message.RecipientType.CC, new InternetAddress(
// "用户名@163.com"));
mm.setSubject("subject1");
mm.setContent("content1", "text/html;charset=utf-8");
return mm;
}
}
代码可直接运行,163邮箱需要申请客户端授权码。
给其他邮箱发送如qq邮箱可能会被当作垃圾邮件,可以对收件地址添加白名单域名(及163邮箱服务器)smtp.163.com