JavaMail:java使用QQ郵箱傳送郵件簡單版。

amenghui發表於2020-11-28

java使用QQ郵箱傳送郵件簡單版。

1. 新增需要的依賴

<!-- JavaMail -->
		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.5</version>
		</dependency>
<!-- JavaMail -->

2. QQ郵箱配置
登入到qq郵箱,進入到設定,賬戶管理。找到以下配置
在這裡插入圖片描述

3. 主要程式碼

import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.personal.front.base.util.Email_Util;

public class EmailSendUtil {
	public static void main(String args[]) {
		try {
//			send_email("","");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void send_email(String email, String msg) throws IOException, AddressException, MessagingException {

		String to = email;	//傳送到哪個郵箱
		String subject = "有新留言!";	//郵件標題
		String content = msg;		//郵件內容
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "smtp.qq.com");
		properties.put("mail.smtp.port", "25");
		properties.put("mail.smtp.auth", "true");
		Authenticator authenticator = new Email_Util("xxxxx@qq.com(填你配置的qq郵箱)", "xx(對應授權碼)");//
		javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
		MimeMessage mailMessage = new MimeMessage(sendMailSession);
		mailMessage.setFrom(new InternetAddress("xxxx@qq.com"));//傳送郵件的地址/就填你的qq郵箱
		// Message.RecipientType.TO屬性表示接收者的型別為TO
		mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		mailMessage.setSubject(subject, "UTF-8");
		mailMessage.setSentDate(new Date());
		// MiniMultipart類是一個容器類,包含MimeBodyPart型別的物件
		Multipart mainPart = new MimeMultipart();
		// 建立一個包含HTML內容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		html.setContent(content.trim(), "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		mailMessage.setContent(mainPart);
		Transport.send(mailMessage);
	}
}

4. 引用到的工具類

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class Email_Util extends Authenticator {
	String userName = null;
	String password = null;

	public Email_Util() {
	}

	public Email_Util(String username, String password) {
		this.userName = username;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication(){
		return new PasswordAuthentication(userName, password);
}
}

結束。

相關文章