SpringBoot发送邮件

1、配置application.properties

#######邮件配置######
#主机
spring.mail.host=
#用户名
spring.mail.username=
#密码
spring.mail.password=
#编码
spring.mail.default-encoding=gb2312
#使用465端口
spring.mail.properties.mail.smtp.ssl.trust=smtp.qq.com
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.port=465
#
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

2、发送邮件的类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 发送邮件
 */
@Component
public class EmailService {

	@Autowired
	private JavaMailSender sender;

	/**
	 * 发送简单文本邮件
	 * @param from	发送方
	 * @param to	接收方
	 * @param subject	主题
	 * @param content	内容
	 */
	public void sendSimpleMail(String from, String[] to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);
		sender.send(message);
	}

	/**
	 * 发送带附件的邮件
	 * @param from	发送方
	 * @param to	接收方
	 * @param subject	主题
	 * @param content	内容
	 * @param file		附件
	 */
	public void sendAttachmentsMail(String from, String to, String subject, String content, File file) throws Exception {
		MimeMessage message = sender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(from);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content);
		FileSystemResource resource = new FileSystemResource(file);
		helper.addAttachment(file.getName(), resource);
		sender.send(message);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值