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("[email protected]"));
		message.setSubject("中文主题");
		message.setRecipients(RecipientType.TO, 
				InternetAddress.parse("[email protected],[email protected],[email protected]"));
		message.setContent("你好啊!这是使用springboot发送给你的", "text/html;charset=utf-8");
		Transport.send(message);//发送邮件
		return "ok";
	}
	
}

你可能感兴趣的:(javaSE,springboot)