Java實現郵件發送

1. 發件人郵箱需要開通SMTP協議

    qq郵箱:https://jingyan.baidu.com/article/6079ad0eb14aaa28fe86db5a.html

    網易郵箱:http://help.163.com/10/0312/13/61J0LI3200752CLQ.html

2. 給項目添加maven依賴

		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.5.0-b01</version>
		</dependency>

3. 代碼實現

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

public class EmailSendUtil {
	// 郵箱服務器
	private String host;

	private String username;
	// 郵箱密碼,若設置了授權碼就填寫授權碼
	private String password;

	private Address[] mail_to;

	private String mail_from;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Address[] getMail_to() {
		return mail_to;
	}

	public void setMail_to(Address[] mail_to) {
		this.mail_to = mail_to;
	}

	public String getMail_from() {
		return mail_from;
	}

	public void setMail_from(String mail_from) {
		this.mail_from = mail_from;
	}

	public EmailSendUtil() {
	}

	/**
	 *
	 * @param host  發送郵箱的服務器的smtp地址
	 * @param username 發件人用戶名
	 * @param password 發件人密碼或授權碼
	 * @param mailto 收件人列表
	 */
	public EmailSendUtil(String host, String username, String password,
						 Address[] mailto) {
		this.host = host;
		this.username = username;
		this.mail_from = username;
		this.password = password;
		this.mail_to = mailto;
	}

	/**
	 * 此段代碼用來發送普通電子郵件
	 *
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 * @throws GeneralSecurityException
	 */
	public void send() throws Exception {
		Properties props = new Properties();
		// 進行郵件服務器用戶認證
		Authenticator auth = new Email_Autherticator();
		// mail.smtp.host :設置發送郵件的服務器
		props.setProperty("mail.smtp.host", host);
		// 授權
		props.setProperty("mail.smtp.auth", "true");
		// 設置郵件發送的協議
		props.setProperty("mail.transport.protocol", "smtp");

		// ssl設置
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		props.setProperty("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.ssl.socketFactory", sf);

		// 設置session和郵件服務器進行通訊
		Session session = Session.getDefaultInstance(props, auth);

		// 編輯郵件內容信息
		MimeMessage message = createMimeMessage(session,mail_from,mail_to);

		// 發送郵件
		Transport.send(message);
	}

	/**
	 * 用來進行服務器對用戶的認證
	 */
	public class Email_Autherticator extends Authenticator {
		public Email_Autherticator() {
			super();
		}

		public Email_Autherticator(String user, String pwd) {
			super();
			username = user;
			password = pwd;
		}

		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	}

	/**
	 * 創建一封只包含文本的簡單郵件
	 *
	 * @param session     session
	 * @param sendMail    發件人郵箱
	 * @param receiveMail 收件人郵箱
	 * @return
	 * @throws Exception
	 */
	public MimeMessage createMimeMessage(Session session, String sendMail, Address[] receiveMail) throws Exception {
		// 1. 創建一封郵件
		MimeMessage message = new MimeMessage(session);

		// 2. From: 發件人
		message.setFrom(new InternetAddress(sendMail, "暱稱", "UTF-8"));

		/*
		 	3. To: 收件人(可以增加多個收件人、抄送、密送)
		 	若只發給單個用戶:message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用戶", "UTF-8"));
		*/
		message.setRecipients(MimeMessage.RecipientType.TO,receiveMail);

		// 4. Subject: 郵件主題
		message.setSubject("主題", "UTF-8");

		// 5. Content: 郵件正文(內容裏可以使用html標籤),例如<h1>溼度超過閥值</h1>
		message.setContent("溼度超過閥值", "text/html;charset=UTF-8");

		// 6. 設置發件時間,下面表示現在就發送
		message.setSentDate(new Date());

		// 7. 設置郵件標題
		message.setHeader("告警名稱", "溼度告警");

		// 8. 保存設置
		message.saveChanges();

		return message;
	}

	/**
	 * 測試方法
	 * @throws Exception
	 */
	public void test() throws Exception {
		//new 收件人
		Address[] mailto = new Address[2];
		/**
		 * new InternetAddress()中的第一個參數爲收件人郵箱地址,第二個參數爲收件人名稱,第三個爲郵件格式
		 */
		mailto[0] = new InternetAddress("******@163.com","某某","UTF-8");
		mailto[1] = new InternetAddress("*****@qq.com","某某的另一個郵箱","UTF-8");

		EmailSendUtil sendEmail = new EmailSendUtil("smtp.qq.com",
				"******@qq.com", "*******", mailto);
		try {
			sendEmail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("finished");
	}
}

4. 可能出現的問題

  STMP錯誤碼:https://blog.csdn.net/weixin_42615847/article/details/103579588

  我在寫的時候遇到了:javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿´ 這個問題,按理來說,535應該是權限校驗失敗,但是我的賬號和授權碼都是對的,測了好幾次,後來用Authenticator把用戶名和密碼封裝了一下,然後就沒有這個問題了。寫代碼的過程中還是要多確認一下,注意細節。

發佈了52 篇原創文章 · 獲贊 4 · 訪問量 2299
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章