使用JavaMail发送邮件

一、背景

  我们在实际开发中,常常会遇到需要使用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 }

 

点赞