Java實現發送郵件


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郵箱設置:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM