1. 程式人生 > >javax.mail 傳送163郵件

javax.mail 傳送163郵件

1,匯入maven依賴:

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
   <groupId>javax.mail</groupId>
   <artifactId>mail</artifactId>
   <version>1.5.0-b01</version>
</dependency>

2,java程式碼示例:

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    /** 發件人 賬號和密碼**/
    public static final String MY_EMAIL_ACCOUNT = "
[email protected]
"; // 密碼,是你自己的設定的授權碼, // 獲取方式:登陸網頁郵箱,設定-》客戶端授權密碼 public static final String MY_EMAIL_PASSWORD = "xxx"; // SMTP伺服器(這裡用的163 SMTP伺服器) public static final String MEAIL_163_SMTP_HOST = "smtp.163.com"; /** 埠號,這個是163使用到的;QQ的應該是465或者875 **/ public static final String SMTP_163_PORT = "25"; /** 收件人 **/ public static final String RECEIVE_EMAIL_ACCOUNT = "
[email protected]
"; public static void main(String[] args) throws AddressException, MessagingException { Properties p = new Properties(); p.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST); p.setProperty("mail.smtp.port", SMTP_163_PORT); p.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT); p.setProperty("mail.smtp.auth", "true"); p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY"); Session session = Session.getInstance(p, new Authenticator() { // 設定認證賬戶資訊 @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD); } }); session.setDebug(true); System.out.println("建立郵件"); MimeMessage message = new MimeMessage(session); // 發件人 message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT)); // 收件人和抄送人 message.setRecipients(Message.RecipientType.TO, RECEIVE_EMAIL_ACCOUNT); // 有些敏感資訊會被郵件伺服器禁止傳送,所以儘量多測試下 message.setSubject("郵件主題"); message.setContent("<h1>郵件內容</h1>" + "今天週末,你有空出去玩嗎?", "text/html;charset=UTF-8" ); message.setSentDate(new Date()); message.saveChanges(); System.out.println("準備傳送"); Transport.send(message); } }