以下是經過本人測試的代碼,將關鍵的地方換成了白文,注意替換。
在編寫之前需要導入一個包:mail.jar
以下便是發送郵件的全部代碼:
package com.mokerson.util;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
/**
* @author TanGuozheng
*/
public class SendEmail {
public void send() {
try {
Properties props = new Properties();
// 設置郵件服務器主機名
props.setProperty("mail.host", "郵箱服務器SMTP 例如:smtp.163.com");
// 設置端口號
props.setProperty("mail.port", "服務器的端口號 例如:465");
// 發送郵件協議名稱
// 設置採用SSL加密傳輸
props.setProperty("mail.transport.protocol", "smtp");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
// 啓用SSL加密傳輸
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// 設置會話
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
// 郵件主題
msg.setSubject("郵件服務");
// 郵件內容信息
msg.setText("中心內容");
msg.setFrom(new InternetAddress("發送的賬號"));
Transport transport = session.getTransport();
// 連接到emailService,使用user賬戶登錄,登錄的密碼爲passWord
transport.connect("郵箱服務器SMTP", "發送的賬號", "此處填寫密碼");
// 發送信息到to的位置。
transport.sendMessage(msg, new Address[] { new InternetAddress("接受郵件的郵箱") });
transport.close();
} catch (MessagingException | GeneralSecurityException e) {
e.printStackTrace();
}
}
}
請確保賬號密碼以及SMTP服務器的正確,如果老鐵遇到了問題,歡迎在評論區留言