springboot发送邮件

package hello.controller;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@SpringBootApplication
@Controller
@EnableScheduling
public class JavaMailController {
	
	@Autowired
	private JavaMailSender mailSender;
	 //利用springboot mail发送
	@RequestMapping("/mail")
	@ResponseBody
	public String sendEmail() throws MessagingException {
	    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
	    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	    // 设置发件人:
	    message.setFrom("你的发件邮箱地址");
	    // 设置收件人:
	    message.setTo("收件邮箱");
	    // 设置标题
	    message.setSubject("This is the message subject");
	    // 设置邮件正文:
	    message.setText("你好,这是我用springBoot发送的邮件,它可能在你的垃圾箱里面");
	    this.mailSender.send(mimeMessage);
	    return "success";
	}

	//传统java方式发送邮件
	@RequestMapping("/mail1")
	@ResponseBody
	public String sendEmail1() throws MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.smtp.auth", "true");//认证
		props.setProperty("mail.transport.protocol", "smtp");//使用协议
		props.setProperty("mail.host", "smtp.163.com");//指定发件人邮件服务器的地址,这里我使用的是163邮箱发送
		//设置发件人用户名和密码
		Session session = Session.getInstance(props,
				new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication(){
							return new PasswordAuthentication("发件邮箱", "密码");
						}
					}
				);
		session.setDebug(true);//加入调试信息
		Message message = new MimeMessage(session);
		message.setText("Hello World!");//邮件内容
		message.setFrom(new InternetAddress("XX@163.com"));
		message.setSubject("中文主题");
		message.setRecipients(RecipientType.TO, 
				InternetAddress.parse("aaa@189.cn,bbb@qq.com,ccc@qq.com"));
		message.setContent("<span style='color:red'>你好啊!这是使用springboot发送给你的<span>", "text/html;charset=utf-8");
		Transport.send(message);//发送邮件
		return "ok";
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值