Simple mail sending and receiving using java mail

During the development process today, I encountered the problem of price reduction notification. If the price drops, send an email to the designated mailbox. By the way, learn how to send and receive simple emails in java.

The java mail api provided by sun company can solve this problem very well. The following are the specific ideas and codes.
1. Sending emails:
It is mainly divided into the following four steps:
a. Create a session for sending and receiving emails (you can use the java.util.properties class to write various parameters, and use the Authencator class to verify the mailbox);
b. Create mimeMessage mail from session object;
c. Create mail sending object Transport from session object;
d. There is sending object to send mail and close transport; the
code is as follows:
public class MailInit {

	/**
	 * Initialize the email sending and receiving Session
	 * @author zhanghao
	 * 20150327
	 * */
	public static Session init(String host,final String username,final String password){
		
		//Initialize email related configuration information
		Properties properties = new Properties();
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.smtp.host", host);
		properties.setProperty("mail.transport.protocol", "smtp"); //Check related?
		properties.setProperty("mail.store.protocol", "pop3"); //Receive mail
		
		//Complete email username and password verification
		Authenticator authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication(username, password);
			}
		};
		//Create a Session for sending and receiving emails
		Session session = Session.getInstance(properties, authenticator);
		return session;
	}
	

/**
	 * Mail sending (single person)
	 * */
	public void sendSingle(String subject,String contect,String username,String password,InternetAddress address){
		String host = MailInit.getHostByUserName(username);
		Session session =MailInit.init(host, username, password);
		
		//create mime mail
		MimeMessage message = new MimeMessage(session);
		try {
			//set sender
			message.setFrom(new InternetAddress(username));
			// set recipient
			message.addRecipient(Message.RecipientType.TO, address);
			//set theme
			message.setSubject("mail subject");
			//set content
			message.setContent(contect,"text/html;charset=utf-8");
			//send email
			Transport.send(message);
			logger.info("Mail sent successfully!!");
		} catch (MessagingException e) {
			String msg = "Failed to send email!!";
			logger.error(msg);
			throw new RuntimeException(msg);
		}
	}
	
	/**
	 * mass mailing
	 * */
	public void sendGroup(String subject,String contect,String username,String password,InternetAddress[] addressGroup){
		String host = MailInit.getHostByUserName(username);
		Session session =MailInit.init(host, username, password);
		
		//create mime mail
		MimeMessage message = new MimeMessage(session);
		try {
			//set sender
			message.setFrom(new InternetAddress(username));
			// set recipient
			message.addRecipients(RecipientType.TO, addressGroup);
			//set theme
			message.setSubject("mail subject");
			//set content
			message.setContent(contect,"text/html;charset=utf-8");
			//send email
			Transport.send(message);
		} catch (MessagingException e) {
			String msg = "Failed to send email!!";
			logger.error(msg);
			throw new RuntimeException(msg);
		}
		
	}
2. Mail receiving is mainly divided into the following steps:
a. Create a session for sending and receiving mail (you can use the java.util.properties class to write various parameters, and use the Authencator class to verify the mailbox);
b. The session object creates the store object to connect to the mailbox;
c. The Folder folder is created by the store object (note: the open method needs to be used to open the folder after the creation is completed);
d. The instance of the Folder calls the getMessage method to return the Message array to get the mail content.
code show as below:
public void receiveMail(String username,String password){
		String host = MailInit.getPop3ByUserName(username);
		Session session =MailInit.init(host, username, password);
		//create store
		Store store;
		try {
			store = session.getStore();
			store.connect(host,110,username,password);  
			//Open the Folder after the connection is complete
			Folder folder = store.getFolder("INBOX"); //INBOX is the only folder that POP3 can use. If using IMAP, other folders are also available.
			folder.open(Folder.READ_ONLY);
			Message[] messages = folder.getMessages();
			for (Message message : messages) {
				System.out.println(message.getSubject());
			}
			logger.info("Receive email successfully!!");
		} catch (MessagingException e) {
			String msg = "Failed to receive mail!!";
			logger.error(msg);
			throw new RuntimeException(msg);
		}
		
	}
Complete code download address: https://github.com/wasapii/JavaMailDemo/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327069684&siteId=291194637