Java实现发送邮件

旧时模样 提交于 2020-12-12 01:03:17

1、发送QQ邮件

 1 import java.util.Properties;
 2 import javax.mail.Message;
 3 import javax.mail.MessagingException;
 4 import javax.mail.Session;
 5 import javax.mail.Transport;
 6 import javax.mail.internet.AddressException;
 7 import javax.mail.internet.InternetAddress;
 8 import javax.mail.internet.MimeMessage;
 9 
10 public class SendQQMailUtil {
11     
12     public static void main(String[] args) throws AddressException,MessagingException {
13         Properties properties = new Properties();
14         properties.put("mail.transport.protocol", "smtp");// 连接协议
15         properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
16         properties.put("mail.smtp.port", 465);// 端口号
17         properties.put("mail.smtp.auth", "true");
18         properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
19         properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
20         // 得到回话对象
21         Session session = Session.getInstance(properties);
22         // 获取邮件对象
23         Message message = new MimeMessage(session);
24         // 设置发件人邮箱地址
25         message.setFrom(new InternetAddress("xxx@qq.com"));
26         // 设置收件人邮箱地址 
27         message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com"),new InternetAddress("xxx@qq.com")});
28         //message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));//一个收件人
29         // 设置邮件标题
30         message.setSubject("xmqtest");
31         // 设置邮件内容
32         message.setText("邮件内容邮件内容邮件内容xmqtest");
33         // 得到邮差对象
34         Transport transport = session.getTransport();
35         // 连接自己的邮箱账户
36         transport.connect("xxx@qq.com", "xxxxxxxxxxxxx");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
37         // 发送邮件
38         transport.sendMessage(message, message.getAllRecipients());
39         transport.close();
40     }
41 }

2、发送163邮箱

 1 import java.io.IOException;
 2 import java.util.*;
 3 
 4 import javax.mail.*;
 5 import javax.mail.internet.*;
 6 import javax.activation.*;
 7 
 8 public class SendMailUtil {
 9 
10     static String HOST = ""; // smtp服务器
11     static String FROM = ""; // 发件人地址
12     static String TO = ""; // 收件人地址
13     static String AFFIX = ""; // 附件地址
14     static String AFFIXNAME = ""; // 附件名称
15     static String USER = ""; // 用户名
16     static String PWD = ""; // 163的授权码
17     static String SUBJECT = ""; // 邮件标题
18     static String[] TOS = null;
19     
20     static {
21         try {
22             Properties props = new Properties(); 
23             props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));//从自定义配置文件获取相关参数
24             HOST=props.getProperty("host");
25             FROM=props.getProperty("from");
26             TO=props.getProperty("to");
27             TOS=TO.split(",");
28             AFFIX=props.getProperty("affix");
29             AFFIXNAME=props.getProperty("affixName");
30             USER=props.getProperty("user");
31             PWD=props.getProperty("pwd");
32             SUBJECT=props.getProperty("subject");
33         } catch (IOException e) {
34             e.printStackTrace();
35         }
36     }
37 
38     /**
39      * 发送邮件
40      * @param host
41      * @param user
42      * @param pwd
43      */
44     public static void send(String context) {
45         Properties props = new Properties();
46         props.put("mail.smtp.host", HOST);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
47         props.put("mail.smtp.auth", "true");  //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
48         Session session = Session.getDefaultInstance(props);//用props对象构建一个session
49         session.setDebug(true);
50         MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象
51         try {
52             message.setFrom(new InternetAddress(FROM));// 加载发件人地址
53             InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加载收件人地址
54             for (int i = 0; i < TOS.length; i++) {  
55                 sendTo[i] = new InternetAddress(TOS[i]);  
56             }
57             message.addRecipients(Message.RecipientType.TO,sendTo);
58             message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错
59             message.setSubject(SUBJECT);//加载标题
60             Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
61             BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容
62             contentPart.setText(context);
63             multipart.addBodyPart(contentPart);
64             if(!AFFIX.isEmpty()){//添加附件
65                  BodyPart messageBodyPart = new MimeBodyPart();
66                  DataSource source = new FileDataSource(AFFIX);
67                  messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的内容
68                  sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//添加附件的标题
69                  messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(AFFIXNAME.getBytes()) + "?=");
70                  multipart.addBodyPart(messageBodyPart);
71             }
72             message.setContent(multipart);//将multipart对象放到message中
73             message.saveChanges(); //保存邮件
74             Transport transport = session.getTransport("smtp");//发送邮件
75             transport.connect(HOST, USER, PWD);//连接服务器的邮箱
76             transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去
77             transport.close();//关闭连接
78         } catch (Exception e) {
79             e.printStackTrace();
80         }
81     }
82     
83 
84 //    public static void main(String[] args) {
85 //        send("内容");
86 //    }
87     
88 }

 或者

 1 import java.util.Properties;
 2 import javax.mail.Message;
 3 import javax.mail.MessagingException;
 4 import javax.mail.Session;
 5 import javax.mail.Transport;
 6 import javax.mail.internet.AddressException;
 7 import javax.mail.internet.InternetAddress;
 8 import javax.mail.internet.MimeMessage;
 9 
10 /*<!-- javax.mai 核心包 -->
11 <dependency>
12  <groupId>javax.activation</groupId>
13  <artifactId>activation</artifactId>
14  <version>1.1</version>
15 </dependency>
16 <dependency>
17  <groupId>javax.mail</groupId>
18  <artifactId>mail</artifactId>
19  <version>1.4.5</version>
20 </dependency>*/
21 
22 public class TestJava {
23     public static void main(String[] args) throws MessagingException {
24         Properties prop=new Properties();
25         prop.put("mail.host","smtp.163.com" );
26         prop.put("mail.transport.protocol", "smtp");
27         prop.put("mail.smtp.auth", true);
28         //使用java发送邮件5步骤
29         //1.创建sesssion
30         Session session=Session.getInstance(prop);
31         //开启session的调试模式,可以查看当前邮件发送状态
32         session.setDebug(true);
33         //2.通过session获取Transport对象(发送邮件的核心API)
34         Transport ts=session.getTransport();
35         //3.通过邮件用户名密码链接
36         ts.connect("13691209103@163.com", "客户端授权码");
37         //4.创建邮件
38         Message msg=createSimpleMail(session);
39         //5.发送电子邮件
40         ts.sendMessage(msg, msg.getAllRecipients());
41     }
42     
43     public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException{
44         //创建邮件对象
45         MimeMessage mm=new MimeMessage(session);
46         //设置发件人
47         mm.setFrom(new InternetAddress("13691209103@163.com"));
48         //设置收件人
49         mm.setRecipient(Message.RecipientType.TO, new InternetAddress("13691209103@163.com"));
50         //设置抄送人
51 //        mm.setRecipient(Message.RecipientType.CC, new InternetAddress(""));
52         // 添加主题
53         mm.setSubject("第一封JAVA邮件!");
54         // 添加邮件内容
55         mm.setContent("咱们开会吧", "text/html;charset=utf-8");
56         return mm;
57     }
58  
59 }

 

3、163邮箱向qq或企业邮箱等发邮件。

  1 package com.feihe.util.mail;
  2 
  3 import java.util.ArrayList; 
  4 import java.util.Date; 
  5 import java.util.List; 
  6 import java.util.Properties; 
  7 import java.util.regex.Matcher; 
  8 import java.util.regex.Pattern;
  9 
 10 import javax.activation.DataHandler;
 11 import javax.activation.DataSource;
 12 import javax.activation.FileDataSource;
 13 import javax.mail.Address; 
 14 import javax.mail.Authenticator; 
 15 import javax.mail.BodyPart; 
 16 import javax.mail.Message; 
 17 import javax.mail.PasswordAuthentication; 
 18 import javax.mail.Session; 
 19 import javax.mail.Transport; 
 20 import javax.mail.internet.InternetAddress; 
 21 import javax.mail.internet.MimeBodyPart; 
 22 import javax.mail.internet.MimeMessage; 
 23 import javax.mail.internet.MimeMultipart;
 24 import javax.mail.internet.MimeUtility;
 25 
 26 import com.sun.mail.util.MailSSLSocketFactory; 
 27   
 28 public class sendMailTest { 
 29     public static void main(String[] args) throws Exception { 
 30         // 配置信息 
 31         Properties pro = new Properties(); 
 32         pro.put("mail.smtp.host", "smtp.163.com"); 
 33         pro.put("mail.smtp.auth", "true"); 
 34         // SSL加密 
 35         MailSSLSocketFactory sf = null; 
 36         sf = new MailSSLSocketFactory(); 
 37         // 设置信任所有的主机 
 38         sf.setTrustAllHosts(true); 
 39         pro.put("mail.smtp.ssl.enable", "true"); 
 40         pro.put("mail.smtp.ssl.socketFactory", sf); 
 41         // 根据邮件的会话属性构造一个发送邮件的Session,这里需要注意的是用户名那里不能加后缀,否则便不是用户名了 
 42         //还需要注意的是,这里的密码不是正常使用邮箱的登陆密码,而是客户端生成的另一个专门的授权码 
 43         MailAuthenticator0 authenticator = new MailAuthenticator0("13691209103", "客户端授权码"); 
 44         Session session = Session.getInstance(pro, authenticator); 
 45         // 根据Session 构建邮件信息 
 46         Message message = new MimeMessage(session); 
 47         // 创建邮件发送者地址 
 48         Address from = new InternetAddress("13691209103@163.com"); 
 49         // 设置邮件消息的发送者 
 50         message.setFrom(from); 
 51         // 验证收件人邮箱地址 
 52         List<String> toAddressList = new ArrayList<>(); 
 53         toAddressList.add("liuruiting@feihe.com"); 
 54         StringBuffer buffer = new StringBuffer(); 
 55         if (!toAddressList.isEmpty()) { 
 56             String regEx = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; 
 57             Pattern p = Pattern.compile(regEx); 
 58             for (int i = 0; i < toAddressList.size(); i++) { 
 59                 Matcher match = p.matcher(toAddressList.get(i)); 
 60                 if (match.matches()) { 
 61                     buffer.append(toAddressList.get(i)); 
 62                     if (i < toAddressList.size() - 1) { 
 63                         buffer.append(","); 
 64                     } 
 65                 } 
 66             } 
 67         } 
 68         String toAddress = buffer.toString(); 
 69         if (!toAddress.isEmpty()) { 
 70             // 创建邮件的接收者地址 
 71             Address[] to = InternetAddress.parse(toAddress); 
 72             // 设置邮件接收人地址 
 73             message.setRecipients(Message.RecipientType.TO, to); 
 74             // 邮件主题 
 75             // message.setSubject("java邮件测试"); 
 76             message.setSubject("为什么错了"); 
 77             // 邮件容器 
 78             MimeMultipart mimeMultiPart = new MimeMultipart(); 
 79             // 设置HTML 
 80             BodyPart bodyPart = new MimeBodyPart(); 
 81             // 邮件内容 
 82             // String htmlText = "java邮件测试111"; 
 83             String htmlText = "为什么错了"; 
 84             bodyPart.setContent(htmlText, "text/html;charset=utf-8"); 
 85             mimeMultiPart.addBodyPart(bodyPart); 
 86             // 添加附件 
 87             List<String> fileAddressList = new ArrayList<String>(); 
 88             fileAddressList.add("C:\\Users\\haw2106\\Desktop\\123.jpg"); 
 89             if (fileAddressList != null) { 
 90                 BodyPart attchPart = null; 
 91                 for (int i = 0; i < fileAddressList.size(); i++) { 
 92                     if (!fileAddressList.get(i).isEmpty()) { 
 93                         attchPart = new MimeBodyPart(); 
 94                         // 附件数据源 
 95                         DataSource source = new FileDataSource(fileAddressList.get(i)); 
 96                         // 将附件数据源添加到邮件体 
 97                         attchPart.setDataHandler(new DataHandler(source)); 
 98                         // 设置附件名称为原文件名 
 99                         attchPart.setFileName(MimeUtility.encodeText(source.getName())); 
100                         mimeMultiPart.addBodyPart(attchPart); 
101                     } 
102                 } 
103             } 
104             message.setContent(mimeMultiPart); 
105             message.setSentDate(new Date()); 
106             // 保存邮件 
107             message.saveChanges(); 
108             // 发送邮件 
109             Transport.send(message); 
110         } 
111     } 
112     } 
113   
114     class MailAuthenticator0 extends Authenticator { 
115          /** 
116           * 用户名 
117           */
118          private String username; 
119          /** 
120           * 密码 
121           */
122          private String password; 
123           
124          /** 
125           * 创建一个新的实例 MailAuthenticator. 
126           * 
127           * @param username 
128           * @param password 
129           */
130          public MailAuthenticator0(String username, String password) { 
131               this.username = username; 
132               this.password = password; 
133          } 
134           
135          public String getPassword() { 
136              return password; 
137          } 
138           
139          @Override
140          protected PasswordAuthentication getPasswordAuthentication() { 
141              return new PasswordAuthentication(username, password); 
142          } 
143           
144          public String getUsername() { 
145              return username; 
146          } 
147           
148          public void setPassword(String password) { 
149              this.password = password; 
150          } 
151           
152          public void setUsername(String username) { 
153              this.username = username; 
154          } 
155   
156 }

 

 

4、关于邮箱服务授权配置自行参考官方文档。

如163邮箱设置:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!