Java发送邮件

1.引入jar包依赖

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

2.Java代码

// 邮箱账号
String emailAcct = "XXX@163.com";
// 密码\安全码
String emailPwd = "XXX";
// 用于连接邮件服务器的参数配置
Properties props = new Properties();
// 协议
props.setProperty("mail.transport.protocol", "smtp");
// 服务器
props.setProperty("mail.smtp.host", "fastsmtphz.qiye.163.com");
// 端口
props.setProperty("mail.smtp.port", "465");
// 使用smtp身份验证
props.setProperty("mail.smtp.auth", "true");
// 开启安全协议
props.setProperty("mail.smtp.ssl.enable", "true");
// 信任所有主机
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.setProperty("mail.smtp.ssl.socketFactory", sf);
// 创建认证对象
Authenticator authenticator = new Authenticator() {
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(emailAcct, emailPwd);
	}
};
// 根据参数配置,创建会话对象
Session session = Session.getInstance(props, authenticator);
// 开启debug模式打印日志
//session.setDebug(true);

// 1. 创建邮件对象
MimeMessage message = new MimeMessage(session);

// 2. From: 发件人
message.setFrom(new InternetAddress(emailAcct));

// 3. To: 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email.getRecipient()));

// 4. Subject: 邮件主题
message.setSubject(email.getSubject(), "UTF-8");

// 5. Content: 邮件正文(可以使用html标签)
message.setContent(email.getContent(), "text/html;charset=UTF-8");

// 6. 设置显示的发件时间
message.setSentDate(new Date());

// 7. 保存前面的设置
message.saveChanges();

// 8. 发送
Transport.send(message);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值