1. 程式人生 > >Java傳送郵件的基本配置與步驟

Java傳送郵件的基本配置與步驟

Java傳送郵件的基本配置與步驟

java

這裡簡單介紹一種利用Java來發送郵件的方法。

MavenPOM.xml檔案載入jar包


<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupId>com.sun.activation</groupId>
    <artifactId>javax.activation</artifactId>
    <version>1.2
.0</version> </dependency>

編寫郵件傳送的工具類

這裡需要編寫一個郵件傳送的工具類,以後在其他的程式碼中只需要呼叫這個工具類,傳入幾個引數就可以直接傳送郵件了。

工具類程式碼

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import
javax.mail.internet.MimeMessage; public class EmailUtils { public static void SendEmailInfoUser(String sendAddress, String title, String content,String copysendAddress) throws Exception { Properties properties = new Properties(); //設定伺服器名稱 properties.setProperty("mail.host"
, "smtp.163.com"); //設定郵件傳輸協議 properties.setProperty("mail.transport.protocol", "smtp"); //設定是否要驗證伺服器使用者名稱和密碼 properties.setProperty("mail.smtp.auth", "true"); // 1.建立客戶端與郵箱伺服器的Session物件 Session session = Session.getInstance(properties); // 2.開啟session的debug模式,方便檢視傳送email的執行狀態 session.setDebug(true); // 3.通過session得到transport傳輸物件 Transport transport = session.getTransport(); // 4.使用使用者名稱密碼連線上郵箱伺服器,此處的密碼需要到郵箱開啟服務設定 transport.connect("smtp.163.com", "[email protected]", "435330wpmail"); // 5.建立郵件 Message message = createSimpleMail(session, sendAddress, title, content,copysendAddress); // 6.傳送郵件 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } private static Message createSimpleMail(Session session, String sendAddress, String title, String content,String copysendAddress) throws Exception{ // 建立郵件物件 MimeMessage message = new MimeMessage(session); // 指明郵件的發件人 message.setFrom(new InternetAddress("[email protected]")); // 指明郵件的收件人 message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendAddress)); // 郵件的標題 message.setSubject(title); // 郵件的內容 message.setContent(content, "text/html;charset=UTF-8") // 設定抄送人 message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copysendAddress)); return message; } }