1. 程式人生 > >SpringBoot快速實現郵件傳送功能-百測百靈

SpringBoot快速實現郵件傳送功能-百測百靈

2018年11月10日星期六 隨筆 筆記 springboot整合郵件傳送 一、匯入依賴包 org.springframework.boot spring-boot-starter-mail 二、開啟服務(一個即可) 在這裡插入圖片描述 三、傳送簡訊:配置郵件客戶端到1069…獲取密碼(每個人不一樣) 四、配置檔案application.yml 等同於application.properties #傳送郵件 層次yml規範

mail:
    password: pcchjrrbgifldegb  //傳送簡訊到1069...獲取的密碼
    default-encoding: UTF-8
    host: smtp.qq.com    //smtp.163.com........
    properties:
      mail:
        smtp:
          starttls:
            enable: true
            required: true
          auth: true
    username:
[email protected]
//收件人地址郵件 application: name: spirng-boot-mail mail: fromMail: addr:[email protected] //發件人郵件地址(可不寫) #我的日誌 logging: level: com: yyg: DEBUG

五、抽取後的程式碼

傳送郵件附帶檔案/簡單傳送郵件
MailService
/**
 * 郵件服務介面
 * Date 2018/11/10
 * @Auther 陽彥剛
 */
public interface MailService {
    /**
     * 傳送帶附件的郵件和傳送簡單郵件 兩個介面
     * @param to 接受者
     * @param subject 標題
     * @param content 傳送內容
     * @param filePath 傳送附件
     */
    void sendAttachmentsMail(String resiveUser,String subject,String content,String filePath);
    void  sendMail(String resiveUser,String subject,String content);
}

MailServiceImpl

package com.yyg.api.impl;
import java.io.File;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.alibaba.dubbo.config.annotation.Service;
import com.yyg.api.MailService;
import com.yyg.utils.EmailSendUtils;
/**
 * 郵件服務類
  * Date 2018/11/10
   * @Auther 陽彥剛
 */
@Service //交給spring建立bean
public class MailServiceImpl implements MailService {
	/**
     * 傳送帶附件的郵件和傳送簡單郵件
     * @param to 接受者
     * @param subject 主題
     * @param content 內容
     * @param filePath 檔案路徑
     */
	@Autowired
	EmailSendUtils emailSendUtils;
	@Override
	public void sendAttachmentsMail(String resiveUser, String subject, String content, String filePath) {
		emailSendUtils.sendAttachmentsMail(resiveUser, subject, content, filePath);
	}
	@Override
	public void sendMail(String resiveUser, String subject, String content) {
		emailSendUtils.sendMail(resiveUser, subject, content);
	}
}

工具類EmailUtils

/**
 *Date 2018/11/10
*@Auther 陽彥剛
*/
    package com.yyg.utils;
    import java.io.File;
    import javax.mail.internet.MimeMessage;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    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.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Service;
    @Component  //交給spring建立bean
    public class EmailSendUtils {
    	@Autowired
    	private JavaMailSender mailSender; //匯入Mail.jar包自帶的類,不用管
    	// 獲取application.yml的值
    	@Value("${mail.fromMail.addr}")
    	private String form; //發件人郵箱地址
    	// 傳送郵件 附帶檔案
    	@Async
    	public void sendAttachmentsMail(String resiveUser, String subject, String content, String filePath) {
    		//建立微型郵件物件
    		MimeMessage message = mailSender.createMimeMessage();
    		try {
    			MimeMessageHelper helper = new MimeMessageHelper(message, true);
    			helper.setFrom(form); //發件人郵件地址
    			helper.setTo(resiveUser); //收件人郵箱地址
    			helper.setSubject(subject); //郵箱標題
    			helper.setText(content);//郵件內容
    			//獲取本地檔案從檔案輸入流
    			FileSystemResource file = new FileSystemResource(new File(filePath));
    			String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    			// 新增多個附件可以使用多條
    			helper.addAttachment(fileName, file);
    			mailSender.send(message);
    			System.out.println("帶附件的郵件傳送成功");
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("傳送帶附件的郵件失敗");
    		}
    	}

//簡單傳送郵件 接上

@Async //可用不管 用於整合Dubbo 消費優化的註解
	public void sendMail(String to, String subject, String content) {
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		mailMessage.setFrom(form);// 發起者
		mailMessage.setTo(to);// 接受者
		mailMessage.setSubject(subject);//傳送郵件的標題
		mailMessage.setText(content);//傳送內容
		try {
			mailSender.send(mailMessage);
			System.out.println("傳送簡單郵件");
		} catch (Exception e) {
			System.out.println("傳送簡單郵件失敗" + e.getMessage());
		}
	}
}

六、測試

package com.yyg.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.yyg.EmailRunApp;
import com.yyg.api.MailService;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=EmailRunApp.class)
public class testEmailSend {
	@Autowired
	MailService mailService;
//附帶檔案傳送郵件測試
	@Test
	public void testSend()throws Exception{
		String filePath="D:\\谷歌下載\\a.jpg";
		mailService.sendAttachmentsMail("[email protected]", "附錄郵件", "昔年殘存終不負,化作巨龍騰飛",filePath);
	}
//簡單傳送郵件測試
	@Test
	public void testSend02()throws Exception{
		mailService.sendMail("[email protected]", "普通傳送郵件", "昔年殘存終不負,化作巨龍騰飛");
	}
}