使用JavaMail傳送郵件

阿豪聊乾貨發表於2016-05-14

一、背景

  我們在實際開發中,常常會遇到需要使用java程式碼進行傳送郵件的需求,我們可以通過這種方式向使用者推送通知等。

二、Java程式碼

  1 package com.hafiz.zhang.mail;
  2 
  3 import java.util.Properties;
  4 
  5 import javax.activation.DataHandler;
  6 import javax.activation.FileDataSource;
  7 import javax.mail.Address;
  8 import javax.mail.BodyPart;
  9 import javax.mail.Message;
 10 import javax.mail.Multipart;
 11 import javax.mail.Session;
 12 import javax.mail.Transport;
 13 import javax.mail.internet.InternetAddress;
 14 import javax.mail.internet.MimeBodyPart;
 15 import javax.mail.internet.MimeMessage;
 16 import javax.mail.internet.MimeMultipart;
 17 
 18 
 19 public class Mail { 
 20 
 21     private MimeMessage mimeMsg; //MIME郵件物件 
 22     private Session session; //郵件會話物件 
 23     private Properties props; //系統屬性 
 24     private boolean needAuth = false; //smtp是否需要認證 
 25     //smtp認證使用者名稱和密碼 
 26     private String username; 
 27     private String password; 
 28     private Multipart mp; //Multipart物件,郵件內容,標題,附件等內容均新增到其中後再生成MimeMessage物件 
 29 
 30     /**
 31      * Constructor
 32      * @param smtp 郵件傳送伺服器
 33      */
 34     public Mail(String smtp){ 
 35         setSmtpHost(smtp); 
 36         createMimeMessage(); 
 37     } 
 38 
 39     /**
 40      * 設定郵件傳送伺服器
 41      * @param hostName String 
 42      */
 43     public void setSmtpHost(String hostName) { 
 44         System.out.println("設定系統屬性:mail.smtp.host = "+hostName); 
 45         if(props == null)
 46             props = System.getProperties(); //獲得系統屬性物件     
 47         props.put("mail.smtp.host",hostName); //設定SMTP主機 
 48     } 
 49 
 50 
 51     /**
 52      * 建立MIME郵件物件  
 53      * @return
 54      */
 55     public boolean createMimeMessage() 
 56     { 
 57         try { 
 58             System.out.println("準備獲取郵件會話物件!"); 
 59             session = Session.getDefaultInstance(props,null); //獲得郵件會話物件 
 60         } 
 61         catch(Exception e){ 
 62             System.err.println("獲取郵件會話物件時發生錯誤!"+e); 
 63             return false; 
 64         } 
 65 
 66         System.out.println("準備建立MIME郵件物件!"); 
 67         try { 
 68             mimeMsg = new MimeMessage(session); //建立MIME郵件物件 
 69             mp = new MimeMultipart(); 
 70 
 71             return true; 
 72         } catch(Exception e){ 
 73             System.err.println("建立MIME郵件物件失敗!"+e); 
 74             return false; 
 75         } 
 76     }     
 77 
 78     /**
 79      * 設定SMTP是否需要驗證
 80      * @param need
 81      */
 82     public void setNeedAuth(boolean need) { 
 83         System.out.println("設定smtp身份認證:mail.smtp.auth = "+need); 
 84         if(props == null) props = System.getProperties(); 
 85         if(need){ 
 86             props.put("mail.smtp.auth","true"); 
 87         }else{ 
 88             props.put("mail.smtp.auth","false"); 
 89         } 
 90     } 
 91 
 92     /**
 93      * 設定使用者名稱和密碼
 94      * @param name
 95      * @param pass
 96      */
 97     public void setNamePass(String name,String pass) { 
 98         username = name; 
 99         password = pass; 
100     } 
101 
102     /**
103      * 設定郵件主題
104      * @param mailSubject
105      * @return
106      */
107     public boolean setSubject(String mailSubject) { 
108         System.out.println("設定郵件主題!"); 
109         try{ 
110             mimeMsg.setSubject(mailSubject); 
111             return true; 
112         } 
113         catch(Exception e) { 
114             System.err.println("設定郵件主題發生錯誤!"); 
115             return false; 
116         } 
117     }
118 
119     /** 
120      * 設定郵件正文
121      * @param mailBody String 
122      */ 
123     public boolean setBody(String mailBody) { 
124         try{ 
125             BodyPart bp = new MimeBodyPart(); 
126             bp.setContent(""+mailBody,"text/html;charset=GBK"); 
127             mp.addBodyPart(bp); 
128 
129             return true; 
130         } catch(Exception e){ 
131         System.err.println("設定郵件正文時發生錯誤!"+e); 
132         return false; 
133         } 
134     } 
135     /** 
136      * 新增附件
137      * @param filename String 
138      */ 
139     public boolean addFileAffix(String filename) { 
140 
141         System.out.println("增加郵件附件:"+filename); 
142         try{ 
143             BodyPart bp = new MimeBodyPart(); 
144             FileDataSource fileds = new FileDataSource(filename); 
145             bp.setDataHandler(new DataHandler(fileds)); 
146             bp.setFileName(fileds.getName()); 
147 
148             mp.addBodyPart(bp); 
149 
150             return true; 
151         } catch(Exception e){ 
152             System.err.println("增加郵件附件:"+filename+"發生錯誤!"+e); 
153             return false; 
154         } 
155     } 
156 
157     /** 
158      * 設定發信人
159      * @param from String 
160      */ 
161     public boolean setFrom(String from) { 
162         System.out.println("設定發信人!"); 
163         try{ 
164             mimeMsg.setFrom(new InternetAddress(from)); //設定發信人 
165             return true; 
166         } catch(Exception e) { 
167             return false; 
168         } 
169     } 
170     /** 
171      * 設定收信人
172      * @param to String 
173      */ 
174     public boolean setTo(String to){ 
175         if(to == null)return false; 
176         try{ 
177             mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); 
178             return true; 
179         } catch(Exception e) { 
180             return false; 
181         }     
182     } 
183 
184     /** 
185      * 設定抄送人
186      * @param copyto String  
187      */ 
188     public boolean setCopyTo(String copyto) 
189     { 
190         if(copyto == null)return false; 
191         try{ 
192         mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto)); 
193         return true; 
194         } 
195         catch(Exception e) 
196         { return false; } 
197     } 
198 
199     /** 
200      * 傳送郵件
201      */ 
202     public boolean sendOut() 
203     { 
204         try{ 
205             mimeMsg.setContent(mp); 
206             mimeMsg.saveChanges(); 
207             System.out.println("正在傳送郵件...."); 
208 
209             Session mailSession = Session.getInstance(props,null); 
210             Transport transport = mailSession.getTransport("smtp"); 
211             transport.connect((String)props.get("mail.smtp.host"),username,password); 
212             transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO)); 
213             transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC)); 
214             //transport.send(mimeMsg); 
215 
216             System.out.println("傳送郵件成功!"); 
217             transport.close(); 
218 
219             return true; 
220         } catch(Exception e) { 
221             System.err.println("郵件傳送失敗!"+e); 
222             return false; 
223         } 
224     } 
225 
226     /**
227      * 呼叫sendOut方法完成郵件傳送
228      * @param smtp
229      * @param from
230      * @param to
231      * @param subject
232      * @param content
233      * @param username
234      * @param password
235      * @return boolean
236      */
237     public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) {
238         Mail theMail = new Mail(smtp);
239         theMail.setNeedAuth(true); //需要驗證
240 
241         if(!theMail.setSubject(subject)) return false;
242         if(!theMail.setBody(content)) return false;
243         if(!theMail.setTo(to)) return false;
244         if(!theMail.setFrom(from)) return false;
245         theMail.setNamePass(username,password);
246 
247         if(!theMail.sendOut()) return false;
248         return true;
249     }
250 
251     /**
252      * 呼叫sendOut方法完成郵件傳送,帶抄送
253      * @param smtp
254      * @param from
255      * @param to
256      * @param copyto
257      * @param subject
258      * @param content
259      * @param username
260      * @param password
261      * @return boolean
262      */
263     public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) {
264         Mail theMail = new Mail(smtp);
265         theMail.setNeedAuth(true); //需要驗證
266 
267         if(!theMail.setSubject(subject)) return false;
268         if(!theMail.setBody(content)) return false;
269         if(!theMail.setTo(to)) return false;
270         if(!theMail.setCopyTo(copyto)) return false;
271         if(!theMail.setFrom(from)) return false;
272         theMail.setNamePass(username,password);
273 
274         if(!theMail.sendOut()) return false;
275         return true;
276     }
277 
278     /**
279      * 呼叫sendOut方法完成郵件傳送,帶附件
280      * @param smtp
281      * @param from
282      * @param to
283      * @param subject
284      * @param content
285      * @param username
286      * @param password
287      * @param filename 附件路徑
288      * @return
289      */
290     public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) {
291         Mail theMail = new Mail(smtp);
292         theMail.setNeedAuth(true); //需要驗證
293 
294         if(!theMail.setSubject(subject)) return false;
295         if(!theMail.setBody(content)) return false;
296         if(!theMail.addFileAffix(filename)) return false; 
297         if(!theMail.setTo(to)) return false;
298         if(!theMail.setFrom(from)) return false;
299         theMail.setNamePass(username,password);
300 
301         if(!theMail.sendOut()) return false;
302         return true;
303     }
304 
305     /**
306      * 呼叫sendOut方法完成郵件傳送,帶附件和抄送
307      * @param smtp
308      * @param from
309      * @param to
310      * @param copyto
311      * @param subject
312      * @param content
313      * @param username
314      * @param password
315      * @param filename
316      * @return
317      */
318     public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) {
319         Mail theMail = new Mail(smtp);
320         theMail.setNeedAuth(true); //需要驗證
321 
322         if(!theMail.setSubject(subject)) return false;
323         if(!theMail.setBody(content)) return false;
324         if(!theMail.addFileAffix(filename)) return false; 
325         if(!theMail.setTo(to)) return false;
326         if(!theMail.setCopyTo(copyto)) return false;
327         if(!theMail.setFrom(from)) return false;
328         theMail.setNamePass(username,password);
329 
330         if(!theMail.sendOut()) return false;
331         return true;
332     }
333 
334 } 

測試程式碼如下:

 1 public static void main(String[] args){
 2     String smtp = "SMTP伺服器";
 3     String from = "發信人";
 4     String to = "收信人";
 5     String copyto = "抄送人";
 6     String subject = "郵件主題";
 7     String content = "郵件內容";
 8     String username="使用者名稱";
 9     String password="密碼";
10      String filename = "附件路徑,如:F:\\筆記<a>\\struts2</a>與mvc.txt";
11     Mail.sendAndCc(smtp, from, to, copyto, subject, content, username, password, filename);
12 }

 

相關文章