分享一个邮件发送的java实例(纯文本,带附件,多人抄送,多人密送)

贴代码:

  1 import javax.activation.DataHandler;
  2 import javax.activation.FileDataSource;
  3 import javax.mail.*;
  4 import javax.mail.internet.*;
  5 import java.util.Date;
  6 import java.util.Properties;
  7 import java.util.logging.Logger;
  8 
  9 /**
 10  * @author kabuqinuo
 11  * @date 2018/7/18 8:53
 12  */
 13 /*发送邮件工具类*/
 14 public class SendMailUtil {
 15 
 16     private static Logger logger = Logger.getLogger(String.valueOf(SendMailUtil.class));
 17 
 18 
 19     //测试方法
 20     public static void main(String[] args) throws Exception {
 21         //boolean a = SendMailUtil.getContenet("18-4-25","上海")
 22         String to = "[email protected]";//接收人
 23         boolean a = SendMailUtil.sendMails("邮件的标题","发送人",to,"(抄送人邮箱可多个可为空)","(密送人邮箱可多个可为空)",SendMailUtil.getContenet(),"(附件可为空)");
 24         System.out.println(a);
 25     }
 26 
 27 
 28     //获取发送的内容
 29     public static String getContenet(){
 30         String content = "";
 31         content = "要发送的邮件内容";
 32         return content;
 33     }
 34 
 35     /*
 36      * 设置发送email的基本参数
 37      * @param title 邮件标题
 38      * @param personal 发送人(邮箱上显示的发送人名称)
 39      * @param to 收件人邮箱
 40      * @param copys 抄送人邮箱
 41      * @param blind 密送人邮箱
 42      * @param content 邮件内容
 43      * @param file 附件
 44      * @return
 45      * @throws Exception
 46      */
 47     public static boolean sendMails(String title, String personal,String to,String copys,String blind,String content,String file) {
 48         Properties prop = new Properties();
 49         prop.setProperty("mail.host", "smtp.sina.com");// 设置服务器地址
 50         prop.setProperty("mail.transport.protocol", "smtp");// 邮件发送协议
 51         prop.setProperty("mail.smtp.auth", "true");// 是否要求身份认证
 52         prop.setProperty("mail.smtp.port", "25"); // SMTP邮件服务器默认端口
 53         //使用JavaMail发送邮件的5个步骤
 54         //1、创建session
 55         Session session = Session.getInstance(prop);
 56         //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
 57         session.setDebug(true);
 58         //2、通过session得到transport对象
 59         Transport ts = null;
 60         try {
 61             ts = session.getTransport();
 62         //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。
 63         try {
 64             ts.connect("smtp.sina.com", "[email protected]", "xxx");//发送者的邮箱及密码
 65         } catch (MessagingException e) {
 66             logger.info("连接邮件服务器错误:");
 67             throw new AdminException(ResultEnum.CONNECTION_FAIL);
 68         }
 69         } catch (NoSuchProviderException e) {
 70             logger.info("连接邮件服务器错误:");
 71             throw new AdminException(ResultEnum.CONNECTION_FAIL);
 72         }
 73         //4、创建邮件
 74         Message message;
 75         try {
 76             if (file == null || file.isEmpty()){
 77                 message = createSimple(session, title, personal, to, copys, blind, content);
 78             }else{
 79                 message = createSimplees(session, title, personal, to, copys, blind, content,file);
 80             }
 81         //5、发送邮件
 82         ts.sendMessage(message, message.getAllRecipients());
 83         ts.close();
 84         return true;
 85         }catch (Exception e){
 86             e.printStackTrace();
 87         }
 88         return false;
 89     }
 90 
 91     /*
 92      * 发送邮件(纯文本)
 93      * @param session
 94      * @param title 邮件标题
 95      * @param personal 发送人(邮箱上显示的发送人名称)
 96      * @param to 收件人邮箱
 97      * @param copys 抄送人邮箱
 98      * @param blind 密送人邮箱
 99      * @param content 邮件内容
100      * @return
101      * @throws Exception
102      */
103     private static MimeMessage  createSimple(Session session,String title, String personal, String to, String copys, String blind, String content) throws Exception {
104         MimeMessage message = new MimeMessage(session);
105         //指明邮件的发件人
106         message.setFrom(new InternetAddress("[email protected]", personal, "UTF-8"));
107         //指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
108         InternetAddress[] tos = new InternetAddress().parse(to);
109         message.setRecipients(Message.RecipientType.TO,tos);
110         //预防一个无语的错误:554 DT:SPM
111         //message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse("[email protected]"));
112         //抄送
113         if (copys != null && !copys.isEmpty()){
114             InternetAddress[] cc = new InternetAddress().parse(copys);
115             message.setRecipients(Message.RecipientType.CC,cc);
116         }
117         if (blind != null && blind.isEmpty()){
118             InternetAddress[] bcc = new InternetAddress().parse(blind);
119             message.setRecipients(Message.RecipientType.BCC,bcc);
120         }
121         //设置发送时间
122         message.setSentDate(new Date());
123         //邮件的标题
124         message.setSubject(title);
125         //邮件的文本内容
126         message.setContent(content, "text/html;charset=UTF-8");
127         // 保存并生成最终的邮件内容
128         message.saveChanges();
129         //返回创建好的邮件对象
130         return message;
131     }
132 
133     /*
134      * 发送邮件(带附件)
135      * @param session
136      * @param title 邮件标题
137      * @param personal 发送人(邮箱上显示的发送人名称)
138      * @param to 收件人邮箱
139      * @param copys 抄送人邮箱
140      * @param blind 密送人邮箱
141      * @param content 邮件内容
142      * @param file 附件
143      * @return
144      * @throws Exception
145      */
146     private static MimeMessage  createSimplees(Session session,String title, String personal, String to, String copys,
147                                              String blind, String content,String file) throws Exception {
148         MimeMessage message = new MimeMessage(session);
149         //指明邮件的发件人
150         message.setFrom(new InternetAddress("[email protected]", personal, "UTF-8"));
151         //指明邮件的收件人,发件人和收件人是一样的,那就是自己给自己发
152         InternetAddress[] tos = new InternetAddress().parse(to);
153         message.setRecipients(Message.RecipientType.TO,tos);
154         //抄送
155         if (copys != null && !copys.isEmpty()){
156             InternetAddress[] cc = new InternetAddress().parse(copys);
157             message.setRecipients(Message.RecipientType.CC,cc);
158         }
159         if (blind != null && blind.isEmpty()){
160             InternetAddress[] bcc = new InternetAddress().parse(blind);
161             message.setRecipients(Message.RecipientType.BCC,bcc);
162         }
163         //设置发送时间
164         message.setSentDate(new Date());
165         //邮件的标题
166         message.setSubject(title);
167 
168         // 要求阅读回执(收件人阅读邮件时会提示回复发件人,表明邮件已收到,并已阅读)
169         message.setHeader("Disposition-Notification-To", "[email protected]");
170 
171         MimeBodyPart text = new MimeBodyPart();
172         text.setContent(content, "text/html;charset=UTF-8");
173 
174         //创建邮件附件
175         MimeBodyPart attach = new MimeBodyPart();
176         DataHandler dh = new DataHandler(new FileDataSource(file));
177         attach.setDataHandler(dh);
178         attach.setFileName(MimeUtility.encodeWord(dh.getName()));
179 
180         //创建容器描述数据关系
181         MimeMultipart mp = new MimeMultipart();
182         mp.addBodyPart(text);
183         mp.addBodyPart(attach);
184         mp.setSubType("mixed");
185 
186         message.setContent(mp);
187         message.saveChanges();
188 
189 
190         //返回创建好的邮件对象
191         return message;
192     }
193 }

以上是一个邮件发送的实例,可以纯文本发送邮件 也可以带着附件发送,至于带图片的 还没有写。

用以上实例本人之前用于企业发送邮件,所以发送者的邮箱可密码是写死的,在64行,如果想自由定义发送人的邮箱和密码,可将其上代码稍微改改,把发送者的邮箱和密码参数提取出来。

以上代码中的某些命名和项目中的某些字段冲突 所以稍微改了改。

如果直接拿以上代码来用,会缺少一个异常处理类,这个异常处理类就是项目的整个异常处理工具,简单来说就是抛出错误提示。其他没什么问题,本人亲测。

猜你喜欢

转载自www.cnblogs.com/ka-bu-qi-nuo/p/10056645.html