码迷,mamicode.com
首页 > 编程语言 > 详细

Java Mail发送简单邮件,完整代码

时间:2014-05-15 11:29:37      阅读:523      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   c   

依赖javax.mail.jar,地址:https://java.net/projects/javamail/pages/Home

完整示例代码如下:

bubuko.com,布布扣
  1 package com.jadic.utils;
  2 
  3 import java.io.UnsupportedEncodingException;
  4 import java.util.ArrayList;
  5 import java.util.Date;
  6 import java.util.List;
  7 import java.util.Properties;
  8 import java.util.regex.Pattern;
  9 
 10 import javax.mail.Authenticator;
 11 import javax.mail.Message;
 12 import javax.mail.MessagingException;
 13 import javax.mail.PasswordAuthentication;
 14 import javax.mail.Session;
 15 import javax.mail.Transport;
 16 import javax.mail.internet.AddressException;
 17 import javax.mail.internet.InternetAddress;
 18 import javax.mail.internet.MimeBodyPart;
 19 import javax.mail.internet.MimeMessage;
 20 import javax.mail.internet.MimeMultipart;
 21 import javax.mail.internet.MimeUtility;
 22 
 23 /**
 24  * 简易邮件发送<br>
 25  * 需提供邮件服务提供商的smtp地址、邮箱账号、密码收件人邮箱<br><br>
 26  * 使用方式:<br>
 27  * 1.实例化JMail对象,适合多次利用相同账号信息发送到相同收件人<br>
 28  * &nbsp;&nbsp; JMail jMail = new JMail(...);<br>
 29  * &nbsp;&nbsp; jMail.sendMail(subject, content);<br>
 30  * 2.直接调用JMail静态方法发送,需每次都将smtp、账号、收件人、内容提供<br>
 31  * &nbsp;&nbsp; JMail.sendMail(smtp, fromUserAddress, fromUserPass,recipients,subject,content);
 32  * @author Jadic
 33  * @created 2014-5-13
 34  */
 35 public class JMail {
 36 
 37     private String smtpHost;// smtp服务器地址
 38     private String userName;// 发送方账号
 39     private String userPass;// 发送方密码
 40     private List<String> recipientList;// 收件人列表
 41 
 42     private Message msg;
 43     private boolean isMailConfigInited;
 44 
 45     private final static String VALID_EMAIL_REGEX = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";
 46     private final static Pattern VALID_EMAIL_PATTERN = Pattern.compile(VALID_EMAIL_REGEX, Pattern.CASE_INSENSITIVE);
 47 
 48     private final static String SEND_MAIL_OK = "OK";
 49     private final static String SEND_MAIL_NO_RECIPIENTS = "Fail:no valid recipient set";
 50 
 51     private JMail(String smtp, String fromUserAddress, String fromUserPass) {
 52         this.smtpHost = smtp;
 53         this.userName = fromUserAddress;
 54         this.userPass = fromUserPass;
 55 
 56         recipientList = new ArrayList<String>();
 57         isMailConfigInited = false;
 58     }
 59 
 60     /**
 61      * @param smtp smtp服务地址
 62      * @param fromUserAddress  发件人邮箱账号
 63      * @param fromUserPass 发件人邮箱密码
 64      * @param recipient 收件人地址(列表),支持多个收件人以";"分割
 65      */
 66     public JMail(String smtp, String fromUserAddress, String fromUserPass, String recipient) {
 67         this(smtp, fromUserAddress, fromUserPass);
 68         String[] recs = recipient.split(";");
 69         for (String rec : recs) {
 70             if (isValidEmail(rec)) {
 71                 this.recipientList.add(rec);
 72             }
 73         }
 74     }
 75 
 76     /**
 77      * @param smtp smtp服务地址
 78      * @param fromUserAddress 发件人邮箱账号
 79      * @param fromUserPass 发件人邮箱密码
 80      * @param recipients  收件人地址列表
 81      */
 82     public JMail(String smtp, String fromUserAddress, String fromUserPass, String... recipients) {
 83         this(smtp, fromUserAddress, fromUserPass);
 84         for (String recipient : recipients) {
 85             if (isValidEmail(recipient)) {
 86                 this.recipientList.add(recipient);
 87             }
 88         }
 89     }
 90 
 91     /**
 92      * @param smtp smtp服务地址
 93      * @param fromUserAddress 发件人邮箱账号
 94      * @param fromUserPass 发件人邮箱密码
 95      * @param recipientList 收件人地址列表
 96      */
 97     public JMail(String smtp, String fromUserAddress, String fromUserPass, List<String> recipientList) {
 98         this(smtp, fromUserAddress, fromUserPass);
 99         for (String recipient : recipientList) {
100             if (isValidEmail(recipient)) {
101                 this.recipientList.add(recipient);
102             }
103         }
104     }
105 
106     /**
107      * 发送邮件,主题默认"default"
108      * @param content  发送内容
109      * @return "ok" 成功发送,否则返回失败提示
110      */
111     public String sendMail(String content) {
112         return sendMail("default", content);
113     }
114 
115     /**
116      * @param subject    邮件主题
117      * @param content    邮件内容
118      * @return "ok" 成功发送,否则返回失败提示
119      */
120     public String sendMail(String subject, String content) {
121         if (this.recipientList.size() <= 0) {
122             return SEND_MAIL_NO_RECIPIENTS;
123         }
124 
125         if (!isMailConfigInited) {
126             try {
127                 initMailConfig();
128             } catch (AddressException e) {
129                 return "fail: address err[" + e.getMessage().trim() + "]";
130             } catch (MessagingException e) {
131                 return "fail: MessagingErr[" + e.getMessage().trim() + "]";
132             }
133         }
134         try {
135             msg.setSentDate(new Date());
136         } catch (MessagingException e) {
137             e.printStackTrace();
138         }
139         try {
140             msg.setSubject(MimeUtility.encodeText(subject, "gbk", "B"));
141 
142             MimeMultipart mmp = new MimeMultipart();
143             MimeBodyPart mbp = new MimeBodyPart();
144             mbp.setContent(content, "text/plain;charset=gbk");
145             mmp.addBodyPart(mbp);
146             msg.setContent(mmp);
147             Transport.send(msg);
148         } catch (UnsupportedEncodingException e) {
149             return "fail: unsupported encoding[" + e.getMessage().trim() + "]";
150         } catch (MessagingException e) {
151             return "fail: MessagingErr[" + e.getMessage().trim() + "]";
152         }
153 
154         return SEND_MAIL_OK;
155     }
156 
157     private void initMailConfig() throws AddressException, MessagingException {
158         Properties props = new Properties();
159         // 发送服务器需要身份验证
160         props.setProperty("mail.smtp.auth", "true");
161         // 设置邮件服务器主机名
162         props.setProperty("mail.host", smtpHost);
163         // 发送邮件协议名称
164         props.setProperty("mail.transport.protocol", "smtp");
165 
166         Session session = Session.getInstance(props, new Authenticator() {
167             @Override
168             protected PasswordAuthentication getPasswordAuthentication() {
169                 return new PasswordAuthentication(userName, userPass);
170             }
171         });
172         msg = new MimeMessage(session);
173         msg.setFrom(new InternetAddress(userName));
174         msg.addRecipients(Message.RecipientType.TO, getRecipients());
175         isMailConfigInited = true;
176     }
177 
178     /**
179      * 
180      * @param smtp    smtp地址
181      * @param fromUserAddress 发件人账号
182      * @param fromUserPass    发件人账号密码
183      * @param recipients 收件人(列表),多个收件人以";"分割
184      * @param subject 邮件主题
185      * @param content 邮件内容
186      * @return "ok" 成功发送,否则返回失败提示
187      */
188     public static String sendMail(String smtp, String fromUserAddress, String fromUserPass, String recipients, String subject,
189             String content) {
190         final String userName = fromUserAddress;
191         final String userPass = fromUserPass;
192         Properties props = new Properties();
193         // 发送服务器需要身份验证
194         props.setProperty("mail.smtp.auth", "true");
195         // 设置邮件服务器主机名
196         props.setProperty("mail.host", smtp);
197         // 发送邮件协议名称
198         props.setProperty("mail.transport.protocol", "smtp");
199 
200         Session session = Session.getInstance(props, new Authenticator() {
201             @Override
202             protected PasswordAuthentication getPasswordAuthentication() {
203                 return new PasswordAuthentication(userName, userPass);
204             }
205         });
206         Message msg = new MimeMessage(session);
207         try {
208             msg.setFrom(new InternetAddress(userName));
209             String[] recipientAry = recipients.split(";");
210             InternetAddress[] recipientsAddress = new InternetAddress[recipientAry.length];
211             for (int i = 0; i < recipientAry.length; i++) {
212                 if (isValidEmail(recipientAry[i])) {
213                     recipientsAddress[i] = new InternetAddress(recipientAry[i]);
214                 }
215             }
216             msg.addRecipients(Message.RecipientType.TO, recipientsAddress);
217             msg.setSentDate(new Date());
218             msg.setSubject(MimeUtility.encodeText(subject, "gbk", "B"));
219 
220             MimeMultipart mmp = new MimeMultipart();
221             MimeBodyPart mbp = new MimeBodyPart();
222             mbp.setContent(content, "text/plain;charset=gbk");
223             mmp.addBodyPart(mbp);
224             msg.setContent(mmp);
225             Transport.send(msg);
226         } catch (UnsupportedEncodingException e) {
227             return "fail: unsupported encoding[" + e.getMessage().trim() + "]";
228         } catch (MessagingException e) {
229             return "fail: MessagingErr[" + e.getMessage().trim() + "]";
230         }
231 
232         return SEND_MAIL_OK;
233     }
234 
235     private InternetAddress[] getRecipients() throws AddressException {
236         if (recipientList.size() > 0) {
237             InternetAddress[] recipients = new InternetAddress[recipientList.size()];
238             for (int i = 0; i < recipients.length; i++) {
239                 recipients[i] = new InternetAddress(this.recipientList.get(i));
240             }
241             return recipients;
242         }
243         return new InternetAddress[0];
244     }
245 
246     private static boolean isValidEmail(String email) {
247         return email != null && VALID_EMAIL_PATTERN.matcher(email).find();
248     }
249 }
bubuko.com,布布扣

 

Java Mail发送简单邮件,完整代码,布布扣,bubuko.com

Java Mail发送简单邮件,完整代码

标签:style   blog   class   code   java   c   

原文地址:http://www.cnblogs.com/jadic/p/3729364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!