package com.wzy.car.exhibition.controller.adver; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Calendar; import java.util.Properties; /** * 發送郵件 * * @author 高飛 * @version v1.0 * @since 2018/6/13 */ @Controller @RequestMapping("/bm") public class bMController { @RequestMapping(value = "/sendEmail",method = RequestMethod.POST) @ResponseBody public String sendEmail(@RequestParam(value = "email") String email){ // 1.創建一個程序與郵件服務器會話對象 Session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP");// 連接協議 props.setProperty("mail.smtp.host", "smtp.163.com");// 連接協議 props.setProperty("mail.smtp.port", "25");// 連接協議 // 指定驗證為true props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.timeout","1000"); // 驗證賬號及密碼,密碼需要是第三方授權碼 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication("發送人郵箱", "授權碼"); } }; Session session = Session.getInstance(props, auth); // 2.創建一個Message,它相當於是郵件內容 MimeMessage message = new MimeMessage(session); try { //防止成為垃圾郵件,披上outlook的馬甲 message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869"); // 設置發送者 message.setFrom(new InternetAddress("發送人郵箱")); // 設置發送方式與接收者 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email)); // 設置主題 message.setSubject("標題"); //創建消息主體 MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("內容主體"); // 創建多重消息 Multipart multipart=new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // 設置郵件消息發送的時間 message.setSentDate(Calendar.getInstance().getTime()); // 設置內容 message.setContent(multipart, "text/html;charset=utf-8"); // 3.創建 Transport用於將郵件發送 Transport.send(message); return "200"; }catch (Exception e){ e.printStackTrace(); return "400"; } } }
轉載自https://blog.csdn.net/qq_37427123/article/details/80689988