javascript
android javamail获取邮件太多太慢_结合 Spring 发送邮件的4种正确姿势,你知道几种?...
一、前言
測試所使用的環(huán)境
測試使用的環(huán)境是企業(yè)主流的SSM 框架即 SpringMVC+Spring+Mybatis。為了節(jié)省時間,我直接使用的是我上次的“SSM項目中整合Echarts開發(fā)”該項目已經(jīng)搭建完成的SSM環(huán)境。
標題說的四種姿勢指的是哪四種姿勢?
如何獲取以及運行我的Demo
Github地址:http://github.com/Snailclimb/…。
你可以選擇直接下載或者直接在DOS窗口運行:git clone https://github.com/Snailclimb/J2ee-Advanced.git命令,這樣項目就被拷貝到你的電腦了。
然后選擇導入Maven項目即可(不懂Maven的可以自行百度學習).
二、準備工作
既然要發(fā)送郵件,那么你首先要提供一個能在第三方軟件上發(fā)送郵件功能的賬號。在這里,我選擇的網(wǎng)易郵箱賬號。
我拿網(wǎng)易郵箱賬號舉例子,那么我們如何才能讓你的郵箱賬號可以利用第三方發(fā)送郵件(這里的第三方就是我們即將編寫的程序)。
大家應該清楚:客戶端和后臺交互數(shù)據(jù)的時候用到了Http協(xié)議,那么相應的,郵箱傳輸也有自己的一套協(xié)議,如SMTP,POP3,IMAP。
開啟POP3/SMTP/IMAP服務
所以,我們第一步首先要去開啟這些服務,如下圖所示:
如果你未開啟該服務的話,運行程序會報如下錯誤(配置文件中配置的密碼是你的授權碼而不是你登錄郵箱的密碼,授權碼是你第三方登錄的憑證):
HTTP Status 500 - Request processing failed; nested exception is org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 550 User has no permissionJavaMail介紹
我們需要用到的發(fā)郵件的核心jar包,所以這里好好介紹一下。
JavaMail是由Sun定義的一套收發(fā)電子郵件的API,不同的廠商可以提供自己的實現(xiàn)類。但它并沒有包含在JDK中,而是作為JavaEE的一部分。廠商所提供的JavaMail服務程序可以有選擇地實現(xiàn)某些郵件協(xié)議,常見的郵件協(xié)議包括:
- SMTP:簡單郵件傳輸協(xié)議,用于發(fā)送電子郵件的傳輸協(xié)議;
- POP3:用于接收電子郵件的標準協(xié)議;
- IMAP:互聯(lián)網(wǎng)消息協(xié)議,是POP3的替代協(xié)議。
這三種協(xié)議都有對應SSL加密傳輸?shù)膮f(xié)議,分別是SMTPS,POP3S和IMAPS。
我們如果要使用JavaMail的話,需要自己引用相應的jar包,如下圖所示:
<dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>相關配置文件
下圖是除了pom.xml之外用到的其他所有配置文件
pom.xml
需要用到的jar包。
<!--spring支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.0.0.RELEASE</version></dependency><!-- 發(fā)送郵件 --><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency><!-- Freemarker --><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.23</version></dependency><!-- velocity模板引擎 --><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-tools</artifactId><version>2.0</version></dependency>mail.properties
#服務器主機名 mail.smtp.host=smtp.163.com #你的郵箱地址 mail.smtp.username=koushuangbwcx@163.com #你的授權碼 mail.smtp.password=cSdN153963000 #編碼格式 mail.smtp.defaultEncoding=utf-8 #是否進行用戶名密碼校驗 mail.smtp.auth=true #設置超時時間 mail.smtp.timeout=20000如果你的授權碼填寫錯誤的話,會報如下錯誤:
TTP Status 500 - Request processing failed; nested exception is org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Error: authentication failedvelocity.properties
input.encoding=UTF-8 output.encoding=UTF-8 contentType=ext/html;charset=UTF-8 directive.foreach.counter.name=loopCounter directive.foreach.counter.initial.value=0applicationContext-email.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"><!--郵件配置 --><context:property-placeholder location="classpath:mail.properties"ignore-unresolvable="true" /><!--配置郵件接口 --><bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="${mail.smtp.host}" /><property name="username" value="${mail.smtp.username}" /><property name="password" value="${mail.smtp.password}" /><property name="defaultEncoding" value="${mail.smtp.defaultEncoding}" /><property name="javaMailProperties"><props><prop key="mail.smtp.auth">${mail.smtp.auth}</prop><prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop></props></property></bean><!-- freemarker --><bean id="configuration"class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"><property name="templateLoaderPath" value="/WEB-INF/freemarker/" /><!-- 設置FreeMarker環(huán)境變量 --><property name="freemarkerSettings"><props><prop key="default_encoding">UTF-8</prop></props></property></bean><!-- velocity --><bean id="velocityEngine"class="org.springframework.ui.velocity.VelocityEngineFactoryBean"><property name="resourceLoaderPath" value="/WEB-INF/velocity/" /><!-- 模板存放的路徑 --><property name="configLocation" value="classpath:velocity.properties" /><!-- Velocity的配置文件 --></bean> </beans>三、開始編寫工具類
我這里說是工具類,其實只是我自己做了簡單的封裝,實際項目使用的話,可能會需要根據(jù)需要簡單修改一下。
所有用到的類如下圖所示:
發(fā)送Text或者HTML格式的郵件的方法
/*** * Text或者HTML格式郵件的方法* * @param text* 要發(fā)送的內容* @param subject* 郵件的主題也就是郵件的標題* @param location* 文件的地址* @param emailAdress* 目的地* @param javaMailSender* 發(fā)送郵件的核心類(在xml文件中已經(jīng)配置好了)* @param type* 如果為true則代表發(fā)送HTML格式的文本* @return* @throws TemplateException*/public String sendMail(String text, String subject, String location, String emailAdress,JavaMailSender javaMailSender, Boolean type) {MimeMessage mMessage = javaMailSender.createMimeMessage();// 創(chuàng)建郵件對象MimeMessageHelper mMessageHelper;Properties prop = new Properties();try {// 從配置文件中拿到發(fā)件人郵箱地址prop.load(this.getClass().getResourceAsStream("/mail.properties"));String from = prop.get("mail.smtp.username") + "";mMessageHelper = new MimeMessageHelper(mMessage, true, "UTF-8");// 發(fā)件人郵箱mMessageHelper.setFrom(from);// 收件人郵箱mMessageHelper.setTo(emailAdress);// 郵件的主題也就是郵件的標題mMessageHelper.setSubject(subject);// 郵件的文本內容,true表示文本以html格式打開if (type) {mMessageHelper.setText(text, true);} else {mMessageHelper.setText(text, false);}// 通過文件路徑獲取文件名字String filename = StringUtils.getFileName(location);// 定義要發(fā)送的資源位置File file = new File(location);FileSystemResource resource = new FileSystemResource(file);FileSystemResource resource2 = new FileSystemResource("D:/email.txt");mMessageHelper.addAttachment(filename, resource);// 在郵件中添加一個附件mMessageHelper.addAttachment("JavaApiRename.txt", resource2);//// 在郵件中添加一個附件javaMailSender.send(mMessage);// 發(fā)送郵件} catch (MessagingException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "發(fā)送成功";}我在sendMail()方法中添加了一個boolean類型的變量type作為標志,如果為ture就表示發(fā)送html格式的郵件否則直接發(fā)送text格式的郵件。實現(xiàn)起來很簡單,我們通過下面的判斷語句就可以實現(xiàn)了
if (type) {//表示文本以html格式打開mMessageHelper.setText(text, true);} else {mMessageHelper.setText(text, false);}效果:
基于FreeMarker模板引擎發(fā)送郵件
下圖是我們用到的FreeMarker模板文件以及Velocity模板文件的位置。
/*** FreeMarker模板格式的郵件的方法* * @param subject* 郵件的主題也就是郵件的標題* @param location* 文件的地址* @param emailAdress* 目的地* @param javaMailSender* 發(fā)送郵件的核心類(在xml文件中已經(jīng)配置好了)* @param freeMarkerConfiguration* freemarker配置管理類* @return* @throws TemplateException*/public String sendMailFreeMarker(String subject, String location, String emailAdress, JavaMailSender javaMailSender,Configuration freeMarkerConfiguration) {MimeMessage mMessage = javaMailSender.createMimeMessage();// 創(chuàng)建郵件對象MimeMessageHelper mMessageHelper;Properties prop = new Properties();try {// 從配置文件中拿到發(fā)件人郵箱地址prop.load(this.getClass().getResourceAsStream("/mail.properties"));String from = prop.get("mail.smtp.username") + "";mMessageHelper = new MimeMessageHelper(mMessage, true);// 發(fā)件人郵箱mMessageHelper.setFrom(from);// 收件人郵箱mMessageHelper.setTo(emailAdress);// 郵件的主題也就是郵件的標題mMessageHelper.setSubject(subject);// 解析模板文件mMessageHelper.setText(getText(freeMarkerConfiguration), true);// 通過文件路徑獲取文件名字String filename = StringUtils.getFileName(location);// 定義要發(fā)送的資源位置File file = new File(location);FileSystemResource resource = new FileSystemResource(file);mMessageHelper.addAttachment(filename, resource);// 在郵件中添加一個附件javaMailSender.send(mMessage);// 發(fā)送郵件} catch (MessagingException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "發(fā)送成功";}/*** 讀取freemarker模板的方法*/private String getText(Configuration freeMarkerConfiguration) {String txt = "";try {Template template = freeMarkerConfiguration.getTemplate("email.ftl");// 通過map傳遞動態(tài)數(shù)據(jù)Map<String, Object> map = new HashMap<String, Object>();map.put("user", "Snailclimb");// 解析模板文件txt = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);System.out.println("getText()->>>>>>>>>");// 輸出的是HTML格式的文檔System.out.println(txt);} catch (IOException e) {// TODO 異常執(zhí)行塊!e.printStackTrace();} catch (TemplateException e) {// TODO 異常執(zhí)行塊!e.printStackTrace();}return txt;}我們通過getText(Configuration freeMarkerConfiguration)方法讀取freemarker模板,返回的格式如下圖所示:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試</title> </head> <body> <h1>你好Snailclimb</h1> </body> </html>其實就是HTML,然后我們就可以像前面發(fā)送HTML格式郵件的方式發(fā)送這端消息了。
email.ftl
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>測試</title> </head> <body> <h1>你好${user}</h1> </body> </html>效果:
不知道為啥,騰訊每次把我使用模板引擎發(fā)的郵件直接放到垃圾箱。大家如果遇到接收不到郵件,但是又沒報錯的情況,可以看看是不是到了自己郵箱的垃圾箱。
基于Velocity模板引擎發(fā)送郵件
/*** * @param subject* 郵件主題* @param location* 收件人地址* @param emailAdress* 目的地* @param javaMailSender* 發(fā)送郵件的核心類(在xml文件中已經(jīng)配置好了)* @param velocityEngine* Velocity模板引擎* @return*/public String sendMailVelocity(String subject, String location, String emailAdress, JavaMailSender javaMailSender,VelocityEngine velocityEngine) {MimeMessage mMessage = javaMailSender.createMimeMessage();// 創(chuàng)建郵件對象MimeMessageHelper mMessageHelper;Properties prop = new Properties();try {// 從配置文件中拿到發(fā)件人郵箱地址prop.load(this.getClass().getResourceAsStream("/mail.properties"));System.out.println(this.getClass().getResourceAsStream("/mail.properties"));String from = prop.get("mail.smtp.username") + "";mMessageHelper = new MimeMessageHelper(mMessage, true, "UTF-8");// 發(fā)件人郵箱mMessageHelper.setFrom(from);// 收件人郵箱mMessageHelper.setTo(emailAdress);// 郵件的主題也就是郵件的標題mMessageHelper.setSubject(subject);Map<String, Object> map = new HashMap<>();// 獲取日期并格式化Date date = new Date();DateFormat bf = new SimpleDateFormat("yyyy-MM-dd E a HH:mm:ss");String str = bf.format(date);map.put("date", str);String content = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email.vm", "UTF-8", map);mMessageHelper.setText(content, true);// 通過文件路徑獲取文件名字String filename = StringUtils.getFileName(location);// 定義要發(fā)送的資源位置File file = new File(location);FileSystemResource resource = new FileSystemResource(file);mMessageHelper.addAttachment(filename, resource);// 在郵件中添加一個附件// mMessageHelper.addAttachment("JavaApiRename.txt", resource2);//// 在郵件中添加一個附件javaMailSender.send(mMessage);// 發(fā)送郵件} catch (MessagingException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "發(fā)送成功";}email.vm
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><body> <h3>今天的日期是:${date}</h3> </body> </html>效果:
controller層
/*** 測試郵件發(fā)送controller* @author Snailclimb*/ @RestController @RequestMapping("mail") public class SendMailController {@Autowiredprivate JavaMailSender javaMailSender;// 在spring中配置的郵件發(fā)送的bean@Autowiredprivate Configuration configuration;@Autowiredprivate VelocityEngine velocityEngine;// text@RequestMapping("send")public String sendEmail() {EmailUtils emailUtils = new EmailUtils();return emailUtils.sendMail("大傻子大傻子大傻子,你好!!!", "發(fā)送給我家大傻子的~", "D:/picture/meizi.jpg", "1361583339@qq.com",javaMailSender, false);}// html@RequestMapping("send2")public String sendEmail2() {EmailUtils emailUtils = new EmailUtils();return emailUtils.sendMail("<p>大傻子大傻子大傻子,你好!!!</p><br/>" + "<a href='https://github.com/Snailclimb'>點擊打開我的Github!</a><br/>","發(fā)送給我家大傻子的~", "D:/picture/meizi.jpg", "1361583339@qq.com", javaMailSender, true);}// freemarker@RequestMapping("send3")public String sendEmail3() {EmailUtils emailUtils = new EmailUtils();return emailUtils.sendMailFreeMarker("發(fā)送給我家大傻子的~", "D:/picture/meizi.jpg", "1361583339@qq.com", javaMailSender,configuration);}// velocity@RequestMapping("send4")public String sendEmail4() {EmailUtils emailUtils = new EmailUtils();return emailUtils.sendMailVelocity("發(fā)送給我家大傻子的~", "D:/picture/meizi.jpg", "1361583339@qq.com", javaMailSender,velocityEngine);} }四、總結
上面我們總結了Spring發(fā)送郵件的四種正確姿勢,并且將核心代碼提供給了大家。代碼中有我很詳細的注釋,所以我對于代碼以及相關類的講解很少,感興趣的同學可以自行學習。最后,本項目Github地址:http://github.com/Snailclimb/…。
作者:SnailClimb鏈接:https://juejin.im/post/5b6cdd0b5188251b1b44be66
總結
以上是生活随笔為你收集整理的android javamail获取邮件太多太慢_结合 Spring 发送邮件的4种正确姿势,你知道几种?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++定义一个动态对象数组_如何在Pyt
- 下一篇: vivado中的rtl中电路图无发生成_