Use spring to send mail (including tests, source code, comments)

Posted by uramagget on Wed, 26 Jun 2019 20:55:55 +0200

This article mainly talks about the use of spring configuration to achieve mail delivery, compared with the previous low-level implementation is much simpler, only a few configurations can be used, so please look down:

Write an interface first

 /**  
* @Title: IMailserdService.java
* @Package org.service
* @Description: TODO The main functions of this method are:
* @author A18ccms A18ccms_gmail_com  
* @date 2017-5-30 10:36:34 a.m.
* @version V1.0  
*/
package org.service;

 /**   
 *    
 * Project name: spring_Schop8   
 * Class name: IMailserdService   
 * Class Description:   
 * Founder: Mu Xiongxiong  
 * Creation time: 10:36:34 a.m. from May to 30, 2017   
 * Modifier: Mu Xiongxiong   
 * Modification time: 10:36:34 a.m. from May to 30, 2017   
 * Amend Notes:   
 * @version    
 *    
 */
public interface IMailsendService {

	/**
	 * 
	* @Title: sendMessage
	* @Description: The main function of this method is to send mail.
	* @param   Settings file  
	* @return  Return type: void   
	* @throws
	 */
	void sendMessage();
}

Then write a class that implements the interface:

 /**  
* @Title: AttMailsendServiceImpl.java
* @Package org.service.impl
* @Description: TODO The main functions of this method are:
* @author A18ccms A18ccms_gmail_com  
* @date 2017-5-30 11:12:02 a.m.
* @version V1.0  
*/
package org.service.impl;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.service.IMailsendService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

 /**   
 *    
 * Project name: spring_Schop8   
 * Class name: AttMailsendService Impl   
 * Class Description: Sending mail using spring
 * Founder: Mu Xiongxiong  
 * Creation time: 11:12:02 a.m. from May to 30, 2017   
 * Modifier: Mu Xiongxiong   
 * Modification time: 11:12:02 a.m. from May to 30, 2017   
 * Amend Notes:   
 * @version    
 *    
 */
public class AttMailsendServiceImpl implements IMailsendService {

	private JavaMailSender javaMailSender;
	
	/**(Non-Javadoc)
	 * <p>Title: sendMessage</p>
	 * <p>Description(Description: Send mail with attachments</p>
	 * @see org.service.IMailsendService#sendMessage()
	 */

	@Override
	public void sendMessage() {
		MimeMessage message = javaMailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(message,true,"utf-8");
			helper.setFrom("jerry@mail.com");
			helper.setTo("tina@mail.com");
			helper.setSubject("Mail with attachments");
			//Ordinary format
			//Heler. setText ("Send an attachment! <a href='http://www.baidu.com'>Baidu Search</a>
			//html format
			helper.setText("Send an attachment!<a href='http://Www.baidu.com'> Baidu Search </a>, true;
			//Add Annex 1
			ClassPathResource file1 = new ClassPathResource("/org/doc/doc.txt");
			helper.addAttachment(file1.getFilename(),file1.getFile());
			//Add Annex 2
			ClassPathResource file2 = new ClassPathResource("/org/doc/text.txt");
			helper.addAttachment(file2.getFilename(), file2.getFile());
			javaMailSender.send(message);
			
		} catch (MessagingException e) {
			// TODO Exception Execution Block!
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Exception Execution Block!
			e.printStackTrace();
		}
		
	}

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

}

The above class can also send mail with attachments, which contains two attachments (files). Let me get them up.


Another is to use templates to send messages in html format:

I implement classes directly:

 /**  
* @Title: CreateMatterServiceImpl.java
* @Package org.service.impl
* @Description: TODO The main functions of this method are:
* @author A18ccms A18ccms_gmail_com  
* @date 2017-5-30 11:46:53 a.m.
* @version V1.0  
*/
package org.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.service.IMailsendService;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

 /**   
 *    
 * Project name: spring_Schop8   
 * Class name: CreateMatterService Impl   
 * Class Description:   
 * Founder: Mu Xiongxiong  
 * Creation time: 11:46:53 a.m. from May to 30, 2017   
 * Modifier: Mu Xiongxiong   
 * Modification time: 11:46:53 a.m. from May to 30, 2017   
 * Amend Notes:   
 * @version    
 *    
 */
public class CreateMatterServiceImpl implements IMailsendService {

	private JavaMailSender javaMailSender;
	private Configuration configuration;
	
	/**(Non-Javadoc)
	 * <p>Title: sendMessage</p>
	 * <p>Description(Description: Send mail using post-template</p>
	 * @see org.service.IMailsendService#sendMessage()
	 */

	@Override
	public void sendMessage() {
		MimeMessage message = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message,true,"UTF-8");
			helper.setFrom("jerry@mail.com");
			helper.setTo("tina@mail.com");
			helper.setSubject("Sending mail using templates");
			helper.setText(getText(),true);
			//Read from the template
			javaMailSender.send(message);
		} catch (MessagingException e) {
			// TODO Exception Execution Block!
			e.printStackTrace();
		}
	}
	
	//Read template
	private String getText(){
		String txt = "";
		try {
			Template template  = configuration.getTemplate("mail.ftl");
			//Transfer dynamic data through map
			Map map = new HashMap();
			map.put("username","Xiong Xiong");
			//Parse template file
			txt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
			} catch (IOException e) {
			// TODO Exception Execution Block!
			e.printStackTrace();
		} catch (TemplateException e) {
				// TODO Exception Execution Block!
				e.printStackTrace();
			}
		
		return txt;
	}
	

	public JavaMailSender getJavaMailSender() {
		return javaMailSender;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

}

The template file is as follows:


Then look at how spring is configured.

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	
	<bean id="mailsender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="mail.com"></property>
		<property name="port" value="25"></property>
		<property name="username"  value="jerry"></property>
		<property name="password"  value="123" ></property>
		<property name="protocol"  value="smtp"></property>
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
			</props>
		</property>
	</bean>
	
	<!-- To configure FreeMarker-->
	<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
		<!-- Specify template file path -->
		<property name="templateLoaderPath" value="org/doc/"></property>
		<!-- Set up freekMarker environment variable -->
		<property name="freemarkerSettings">
			<props>
				<prop key="default_encoding">UTF-8</prop>
			</props>
		</property>
	</bean>
	<!-- Simple mail -->
	<bean id="simpleMailsendService" class="org.service.impl.SimpleMailsendServiceImpl">
		<property name="sender" ref="mailsender"></property>
	</bean>
	<!-- html And mail with attachments -->
	<bean id="AttMailsendService" class="org.service.impl.AttMailsendServiceImpl">
		<property name="javaMailSender" ref="mailsender"></property>
	</bean>
	<!-- Sending mail using templates-->
	<bean id="createMatterService" class="org.service.impl.CreateMatterServiceImpl">
		<property name="configuration" ref="freeMarkerConfiguration"></property>
		<property name="javaMailSender" ref="mailsender"></property>
	</bean>
	
</beans>

It's already over 00 o'clock, tired and sleepy. I won't explain the content of this application Contexct. XML in detail. There are annotations in it. You can comment if you don't understand it. I'll improve it for the first time.

Then let's test:

TestMail:

package org.test;

import org.junit.Test;
import org.service.IMailsendService;
import org.service.impl.Mail;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMail {
	
	@Test
	public void testMail() {
		ApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml"); 
		//Simple mail
		//IMailsendService mailsendService=(IMailsendService) ctx.getBean("simpleMailsendService");
		
		//Complex mail
		//IMailsendService mailsendService=(IMailsendService) ctx.getBean("AttMailsendService");
		
		//Files using templates
		IMailsendService mailsendService=(IMailsendService) ctx.getBean("createMatterService");
		mailsendService.sendMessage();
		System.out.println("Send successfully!");
	}
	
	
}

Note: Simple mail is text content sent directly, complex mail contains html format and attachments, and template sending is another way of html format.

Let's look at the results of the operation:

First, look at the attachments and html-formatted mail:


Next is a simple email:


The next one is to use the template to send mail. The username is dynamic.



Understand the welcome message!

Topics: Java FreeMarker Spring xml