Send mail with JavaMail

Posted by wenquxing on Fri, 31 Dec 2021 06:22:01 +0100

I Mail protocol:

Sending and receiving mail has the same mail transmission protocol as HTTP protocol

  1. SMTP: (Simple Mail Transfer Protocol)
  2. POP3: (Post Office Protocol Version 3) mail receiving protocol

  3. IMAP: (Internet Message Access Protocol)

II Mail sending and receiving diagram

1. Send mail to the same mail server (163 mailbox example):

2. Send mail to different mail servers:

 

III Mail server name:

The port number of the smtp server is 25 and the server name is smtp xxx. xxx.

The port number of the pop3 server is 110 and the server name is pop3 xxx. xxx

IV JavaMail

1. General

  • Required jar package: mail jar,activation.jar
  • Session: indicates the session, that is, the session between the client and the mail server! To get the session, you need to give the account and password, and of course, the server name. The session object in the mail service is equivalent to the Connection object when connecting to the database.

  • MimeMessage: represents a mail class, which is a subclass of Message. It contains the subject (title), content, recipient address and sender address of the e-mail, CC and BCC can also be set, and even attachments can be set.

  • Transport: used to send mail. It's a transmitter!

2. Steps for sending mail by JavaMail:

Step 1: obtain Session

Session session = Session.getInstance(Properties prop, Authenticator auth);

prop needs to specify two key values, one is to specify the server host name, and the other is to specify whether authentication is required! Of course we need certification!

Properties prop = new Properties();

prop.setProperty(“mail.host”, “smtp.163.com”);// Set server host name

prop.setProperty(“mail.smtp.auth”, “true”);// Setting requires authentication

Authenticator is an interface that represents an authenticator, that is, verifying the identity of the client. We need to implement this interface ourselves. To implement this interface, we need to use an account and password.

Authenticator auth = new Authenticator() {

    public PasswordAuthentication getPasswordAuthentication () {

        new PasswordAuthentication(“itcast_cxf”, “itcast”);// User name and password

}

};

Through the above preparation, you can now obtain the Session object:

Session session = Session.getInstance(prop, auth);

Step 2: create MimeMessage object

To create a MimeMessage, you need to use the Session object to create:

MimeMessage msg = new MimeMessage(session);

Then you need to set the sender address, recipient address, subject, and email body.

msg.setFrom(new InternetAddress(“ xxx@163.com ”));// Set sender

msg.addRecipients(RecipientType.TO, “ xxx@qq.com,xxx@sina.com ”);// Set multiple recipients

msg.addRecipients(RecipientType.CC, “ xxx@sohu.com,xxx@126.com ”);// Set multiple CC

msg.addRecipients(RecipientType.BCC, ” xxx@hotmail.com ”);// Set dark feed

msg.setSubject("email subject -- Practice email sending")// Set theme (title)

msg.setContent("body of course!", “text/plain;charset=utf-8”);// Set body

Step 3: send mail

Transport.send(msg);// Send mail

JavaMail sends mail with attachments (learn)

An email can contain n body and attachments, so the body and N attachments are a part of the email.

In the above hello world case, only the email with the body is sent! Therefore, the body is directly set when calling setContent() method. If you want to send an email with attachments, you need to set the content of the email as MimeMultiPart.

MimeMulitpart parts = new MimeMulitpart();// Multi part objects can be understood as a collection of parts

msg.setContent(parts);// Set the content of the message as multi part content.

Then we need to create the body and N attachments as "main body part" objects and add them to MimeMuiltPart.

MimeBodyPart part1 = new MimeBodyPart();// Create an assembly

part1.setCotnent("this is the body", "text/html;charset=utf-8")// Set content for part

parts.addBodyPart(part1);// Add an assembly to the assembly set.

Let's create an attachment:

MimeBodyPart part2 = new MimeBodyPart();// Create an assembly

part2.attachFile(“F:\a.jpg”);// Set attachment

part2.setFileName(“hello.jpg”);// Set attachment name

parts.addBodyPart(part2);// Add attachments to assembly set

Note that if Chinese is included in the file name when setting the file name, you need to use the MimeUitlity class to encode Chinese:

part2. Setfilename (mimeuitty. Encodetext ("picture. jpg");

Illustration:

V Case presentation:

package cn.itcast.javamail;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.junit.Test;

import cn.itcast.mail.AttachBean;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

public class Demo1 {
	@Test
	public void fun1() throws  Exception{
		/*
		 * 1.Get Session
		 */
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.163.com");//Set server host name
		props.setProperty("mail.smtp.auth", "true");//Is certification required
		
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication("srnmwj", "DYPDXSNMFWFFVZ**");//This is your own activation code
			}
		};
		
		Session session = Session.getInstance(props,auth);
		
		/*
		 * 2.Create MImeMessage
		 */
		
		MimeMessage msg = new MimeMessage(session);
		//Set sender
		msg.setFrom(new InternetAddress("srnmwj@163.com"));
		//Set recipient
		msg.setRecipients(RecipientType.TO, "srnmwj@126.com");
		
		msg.setSubject("This is a study letter for Ma Wenjun Mail Practice mail at");
		msg.setContent("This email is meaningless,It's for practice", "text/html;charset=utf-8");
		
		/*
		 * 3.send out
		 */
		Transport.send(msg);
	}
	/*
	 * Messages with attachments
	 */
	@Test
	public void fun2() throws Exception{
		/*
		 * 1.Get Session
		 */
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication("srnmwj", "DYPDXSNMFWFFVZ**");
			}
		};
		
		Session session = Session.getInstance(props,auth);
		
		/*
		 * 2.Create MImeMessage
		 */
		
		MimeMessage msg = new MimeMessage(session);
		//Set sender
		msg.setFrom(new InternetAddress("srnmwj@163.com"));
		//Set recipient
		msg.setRecipients(RecipientType.TO, "srnmwj@126.com");
		
		msg.setSubject("This is a study letter for Ma Wenjun Mail Practice mail at-With accessories");
		
		/
		/*
		 *When sending a message with attachments, the message body is in the form of multiple parts
		 *1.Create a multipart mail content! MimeMultipart
		 * MimeMultipart Is a collection used to load multiple parts
		 * 2.We need to create two main parts, one is the text content and the other is the attachment
		 * 	The subject is called MimeBodyPart
		 * 3.Set MimeMultiPart to the content of MimeMessage
		 * 
		 */
		MimeMultipart list = new MimeMultipart();//Create a multi assembly host
		//Create MimeBodyPart
		MimeBodyPart part1 = new MimeBodyPart();
		//Set body part content
		part1.setContent("This is a spam message with attachments", "text/html;charset=utf-8");
		//Add the host assembly to the collection
		list.addBodyPart(part1);
		
		//Create MimeBodyPart
		MimeBodyPart part2 = new MimeBodyPart();
		part2.attachFile(new File("F:/JAVA cattle.jpg"));
		//Deal with Chinese garbled code -- display file name
		part2.setFileName(MimeUtility.encodeText("JAVA cattle.jpg"));
		list.addBodyPart(part2);
		
		msg.setContent(list);//Set it to the message as the message content
		
		
		
		
		/*
		 * 3.send out
		 */
		Transport.send(msg);
	}
	@Test
	public void fun3() throws Exception{
		/*
		 * 1.Get session
		 */
		Session session = MailUtils.createSession("smtp.163.com", "srnmwj", "DYPDXSNMFWFFVZ**");
		//Create mail object
		Mail mail = new Mail("srnmwj@163.com","srnmwj@126.com","Ma Wenjun, come on!", "Here is the text");
		//Create attachment object
		AttachBean ab1 = new AttachBean(new File("F:/JAVA cattle.jpg"),"java.jpg");
		//Add to mail
		mail.addAttach(ab1);
		
		//send out
		MailUtils.send(session, mail);
	}
}

*Mailbox settings when sending mail:

Note: the activation code must be remembered!!!

Renderings:

Topics: Java Eclipse JavaEE Tomcat