JavaMail send mail

JavaMail, as the name suggests, provides a programming interface     for developers to deal with e-mail . It is an API released by Sun to handle email. It can conveniently perform some commonly used mail transfers.

 

One: Mailbox Agreement

Common mail protocols are SMTP, POP3, and IMAP.

1. SMTP protocol

SMTP is called Simple Mail Transfer Protocol, which can provide users with an efficient and reliable mail transmission method. An important feature of SMTP is that it can forward emails during transmission, that is, emails can be forwarded to other mail servers through mail servers on different networks.

The SMTP protocol works in two situations: one is the transmission of e-mail from the client to the mail server; the other is the transmission from one mail server to another. SMTP is a request/response protocol, which listens on port 25 to receive mail requests from users and establish an SMTP connection with a remote mail server.

2. POP3 protocol

POP is called the Post Office Protocol and is used to receive e-mails. It uses port 110 of TCP. The third version is commonly used, so it is referred to as POP3 for short.

POP3 still adopts C/S working mode. When the client needs service, the client software (such as Outlook Express) will establish a TCP connection with the POP3 server, and then go through three working states of the POP3 protocol: the first is the authentication process, which confirms the user name and password provided by the client; After passing, it will enter the processing state. In this state, the user can receive his own mail. After completing the corresponding operation, the client will issue the quit command; after that, it will enter the update state and delete the mail marked for deletion from the server. So far, the entire POP process is complete.

3. IMAP protocol

IMAP is called Internet Information Access Protocol, which mainly provides a protocol for obtaining information through the Internet. Like POP3, IMAP provides a convenient mail download service, allowing users to read offline, but IMAP can accomplish far more than that. The summary browsing function provided by IMAP allows you to make a decision whether to download or not after reading all the information such as arrival time, subject, sender, and size of the mail.

 

 

Two: JavaMail package

 

The core classes in the JavaMail package for handling email are: Properties , Session , Message , Address , Authenticator , Transport , Store , etc.

 

①Properties

// own email

public static String myEmailAccount = "[email protected]";

//Authorization code (password for logging in with a third-party tool)

public static String myEmailPassword = "XXXXXXXXXXXXX";

// The SMTP server address of the sender's mailbox, the format is: smtp.xxx.com

public static String myEmailSMTPHost = "smtp.qq.com";

// recipient email

public String receiveMailAccount = "[email protected]";

Public static String smtpPort = "587";

configure

// 1. Create a parameter configuration for connecting to the mail server

 Properties prop = new Properties(); // parameter configuration

 prop.setProperty("mail.transport.protocol", "smtp"); //

// Protocol used (required by the JavaMail specification)

 prop.setProperty("mail.smtp.host", myEmailSMTPHost); // SMTP of sender's mailbox

// server address

prop.setProperty("mail.smtp.auth", "true"); // requires authentication

prop.setProperty("mail.smtp.port", smtpPort);

prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

prop.setProperty("mail.smtp.socketFactory.fallback", "true");

prop.setProperty("mail.smtp.socketFactory.port", smtpPort);


②Session

Session 表示一个邮件会话。

Session 的主要作用包括两个方面:

接收各种配置属性信息:通过 Properties 对象设置的属性信息

初始化 JavaMail 环境:根据 JavaMail 的配置文件,初始化 JavaMail 环境,以便通过 Session 对象创建其他重要类的实例。

Session session = Session.getInstance(prop);

 

③Message

MimeMessage 类:代表整封邮件。

要创建一个 Message ,需要将 Session 对象传递给 MimeMessage 构造器:

MimeMessage message = new MimeMessage(session);

注意:还存在其它构造器,如用按 RFC822 格式的输入流来创建消息。

setFrom :设置邮件的发件人

setRecipient :设置邮件的发送人、抄送人、密送人

三种预定义的地址类型是:

Message.RecipientType.TO :收件人

Message.RecipientType.CC :抄送人

Message.RecipientType.BCC :密送人

setSubject :设置邮件的主题

setContent :设置邮件内容

setText :如果邮件内容是纯文本,可以使用此接口设置文本内容。

 

 

④Address

创建了 Session 和 Message ,并将内容填入消息后,就可以用 Address 确定信件地址了。和 Message 一样, Address 也是个抽象类。用的是 javax.mail.internet.InternetAddress 类。

若创建的地址只包含电子邮件地址,只要传递电子邮件地址到构造器就行了。

例:

Address address = new InternetAddress("[email protected]");

 

⑤Transport

邮件操作只有发送或接收两种处理方式。

JavaMail 将这两种不同操作描述为传输( javax.mail.Transport )和存储( javax.mail.Store ),传输对应邮件的发送,而存储对应邮件的接收。

getTransport : Session 类中的 getTransport () 有多个重载方法,可以用来创建 Transport 对象。

connect : 如果设置了认证命令—— mail.smtp.auth ,那么使用 Transport 类的 connect 方法连接服务器时,则必须加上用户名和密码。

sendMessage : Transport 类的 sendMessage 方法用来发送邮件消息。


⑥Store

getStore : Session 类中的 getStore () 有多个重载方法,可以用来创建 Store 对象。

connect : 如果设置了认证命令—— mail.smtp.auth ,那么使用 Store 类的 connect 方法连接服务器时,则必须加上用户名和密码。

getFolder : Store 类的 getFolder 方法可以 获取邮箱内的邮件夹 Folder 对象

close : Store 类的 close 方法用来关闭和邮件服务器的连接。


三:程序操作邮箱发送邮件

· 创建Properties对象配置属性。

· 创建一个 Session 对象。

· Session对象创建一个 Message 对象 ( 也就是邮件内容 ) 。

· Session 对象创建一个 Transport 对象 /Store 对象,用来发送 / 保存邮件。

· Transport 对象发送邮件; Store 对象获取邮箱的邮件。

 

1:将邮箱的smtp服务开启  (QQ邮箱)

 

2:

 

封装发送邮件

package TestJavaEmail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MyEmail {
	//发件人的邮箱
	public static String myEmailAccount = "[email protected]";
	//授权码(第三方登陆的密码)
	public static String myEmailPassword = "ldejlufrfbsybfbe";
	// 发件人邮箱的 SMTP 服务器地址, 一般格式为 smtp.xxx.com
	public static String myEmailSMTPHost = "smtp.qq.com";
	// 收件人邮箱
	public  String receiveMailAccount = null;
	public static  String smtpPort = "587";

	public  String getReceiveMailAccount() {
		return receiveMailAccount;
	}

	public  void setReceiveMailAccount(String receiveMailAccount) {
		this.receiveMailAccount = receiveMailAccount;
	}
	
	public MyEmail(String receiveMailAccount) {
		super();
		this.receiveMailAccount = receiveMailAccount;
	}

	public MyEmail() {
		super();
	}

	/**
	 * 封装邮件
	 * 
	 * @param session
	 * @param sendMail
	 * @param receiveMail
	 * @return 邮件对象
	 * @throws Exception
	 */
//创建邮件
	public  MimeMessage getMimeMessage(Session session, String sendMail, String receiveMail,Object content) throws Exception {
		// 1.创建邮件对象
		MimeMessage message = new MimeMessage(session);
		// 2.from:发件人
		// 其中 InternetAddress 的三个参数分别为:
		// 邮箱必须是真实有效的邮箱。, 显示的昵称(只用于显示), 昵称的字符集编码
		// Address是抽象类->InternetAddress是实现类
		message.setFrom(new InternetAddress(sendMail, "小草帽(Maps)", "UTF-8"));

		// 3. to收件人。
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "LJY", "UTF-8"));
		// To: 增加收件人(可选)
		// message.addRecipient(MimeMessage.RecipientType.TO, new
		// InternetAddress("[email protected]", "USER_DD", "UTF-8"));
		// Cc: 抄送(可选)
		// message.setRecipient(MimeMessage.RecipientType.CC, new
		// InternetAddress("[email protected]", "USER_EE", "UTF-8"));
		// Bcc: 密送(可选)
		// message.setRecipient(MimeMessage.RecipientType.BCC, new
		// InternetAddress("[email protected]", "USER_FF", "UTF-8"));

		// 4:设置邮件主题
		message.setSubject("MyEmail", "UTF-8");
		// 5. Content: 邮件正文(可以使用html标签)
		message.setContent(content, "text/html;charset=UTF-8");
		// 6. 设置显示的发件时间  java.util.Date类型
		message.setSentDate(new Date());
		// 7. 保存前面的设置
		message.saveChanges();
		// 8. 将该邮件返回
		return message;
	}

	
//将信件内容传递进来
	public  void sendEmail(Object content) throws Exception {
		
			// 1. 创建参数配置, 用于连接邮件服务器的参数配置
			Properties prop = new Properties();
			prop.setProperty("mail.transport.protocol", "smtp");
			// 使用的协议(JavaMail规范要求)
			prop.setProperty("mail.smtp.host", myEmailSMTPHost);
			// 发件人的邮箱的 SMTP,服务器地址
			prop.setProperty("mail.smtp.auth", "true");
			// 需要请求认证
			// 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启)。
			// 如果无法连接邮件服务器, 开启 SSL 安全连接。

			// SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加
			// 如果开启了 SSL 连接,需要改为对应邮箱的 SMTP 服务器的端口
			// QQ邮箱的SMTP(SLL)端口为465或587。
			prop.setProperty("mail.smtp.port", smtpPort);
			prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			prop.setProperty("mail.smtp.socketFactory.fallback", "true");
			prop.setProperty("mail.smtp.socketFactory.port", smtpPort);

			// 2. 根据配置创建会话对象, 用于和邮件服务器交互
			Session session = Session.getInstance(prop);
			session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
			// 3. 创建一封邮件
			MimeMessage message = getMimeMessage(session, myEmailAccount, receiveMailAccount,content);
			// 4. 根据 Session 获取邮件传输对象
			Transport transport = session.getTransport();
			// 5.绑定自己的邮箱和发送目标的邮箱
			transport.connect(myEmailAccount, myEmailPassword);
			// 6. 发送邮件, 发到所有的收件地址抄送人, 密送人
			// message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人
			transport.sendMessage(message, message.getAllRecipients());
			// 7. 关闭连接
			transport.close();
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325433542&siteId=291194637