前言
前段時間做一個緊急的功能,其中有部分需求是需要發郵件通知;通過查閱以及實驗,很快的寫了個發送郵件的功能;現在整理一下記錄下來。
發送郵件
一、在pom中引入相關依賴
1
2
3
4
5
6
7
8
9
10
11
|
<dependency> <groupid>javax.mail</groupid> <artifactid>javax.mail-api</artifactid> <version> 1.5 . 6 </version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-email</artifactid> <version> 1.4 </version> </dependency> |
二、發送郵件的工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
package com.zhanghan; import org.apache.commons.mail.emailexception; import org.apache.commons.mail.htmlemail; import org.springframework.stereotype.service; import org.springframework.util.stringutils; import java.util.arraylist; import java.util.list; @service public class emailserviceimpl implements emailservice { @override public void sendmail(string address, string subject, string htmlmsg, boolean isssl) throws emailexception { if (stringutils.isempty(address) || stringutils.isempty(subject) || stringutils.isempty(htmlmsg)) { throw new emailexception(); } try { htmlemail email = new htmlemail(); list<string> list = new arraylist<string>(); list.add(address); string[] tos = list.toarray( new string[list.size()]); // 這里是smtp發送服務器的名字:163的如下:"smtp.163.com" email.sethostname( "smtp.exmail.qq.com" ); if (isssl) { email.setsslonconnect( true ); email.setsmtpport( 465 ); } // 字符編碼集的設置 email.setcharset( "utf-8" ); // 收件人的郵箱 email.addto(tos); // 發送人的郵箱以及發件人名稱 email.setfrom( "xxx@163.com" , "zhanghan" ); // 如果需要認證信息的話,設置認證:用戶名-密碼。分別為發件人在郵件服務器上的注冊名稱和密碼 email.setauthentication( "xxx@163.com" , "yyyy" ); // 要發送的郵件主題 email.setsubject(subject); // 要發送的信息,由于使用了htmlemail,可以在郵件內容中使用html標簽 email.sethtmlmsg(htmlmsg); string result1 = email.send(); } catch (exception e) { e.printstacktrace(); throw new emailexception(); } } } |
三、遇到的坑
在本地測試沒有問題;我們的測試服務在阿里云上,阿里云對發送的時候是失敗;追蹤日志發現原來是阿里云將發送郵件的默認端口25關閉;需要將端口改成465。
總結
1、遇到問題要多看日志,追蹤問題;
2、不斷積累,不斷完善自己知識體系。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zhanghan18333611647/article/details/81265682