package com;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
//以163邮箱为例
public class Main {
// 设置邮箱账户
public static String myEmailAccount = "xxx@163.com";
// 邮箱密码 注:密码不是邮箱的登录密码,是 授权码
public static String myEmailPassword = "xxxx";
// 邮箱 SMTP 协议
public static String myEmailSMTPHost = "smtp.163.com";
// 收件人账户
public static String receiveMailAccount = "xxxx@xxx.com";
public static void main(String[] args) throws Exception{
Properties props = new Properties(); //用于连接邮件服务器的参数配置(发送邮件时需要用到)
props.setProperty("mail.transport.protocal", "smtp"); //加载SMTP协议
props.setProperty("mail.smtp.host", myEmailSMTPHost); //验证协议
props.setProperty("mail.smtp.auth", "true"); //验证为真
Session session = Session.getDefaultInstance(props);
session.setDebug(true); //开启Debug 打印信息
/** 生成一封新邮件 **/
MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);
//开启邮件发送
Transport transport = session.getTransport();
//确认账户密码
transport.connect(myEmailAccount, myEmailPassword);
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
//关闭
transport.close();
}
//生成邮件方法
private static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMailAccount) throws Exception{
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//发件人
message.setFrom(new InternetAddress(sendMail, "xxxxxx", "UTF-8"));
//TO:收件人 、 CC:抄送人、BCC:密送
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount, "xx", "UTF-8"));
//邮件主题
message.setSubject("xxxxx", "UTF-8");
//邮件内容
message.setContent("赶快买根雪糕压压热气吧。", "text/html;charset=UTF-8");
//时间
message.setSentDate(new Date());
//保存
message.saveChanges();
//返回邮件
return message;
}
}