Spring – 使用JavaMailSender发送电子邮件

Spring – 使用JavaMailSender发送电子邮件

原文: https://howtodoinjava.com/spring-core/send-email-with-spring-javamailsenderimpl-example/

在 Spring 5 提供的JavaMailSender接口中学习发送电子邮件。 这是通过 gmail smtp 服务器发送电子邮件的分步示例。

我们将使用javax.mail maven 依赖来发送电子邮件,同时在实现JavaMailSender接口的JavaMailSenderImpl类中配置邮件属性。

了解更多:使用 Gmail SMTP 服务器发送电子邮件(javax.email)

1. Maven 依赖

请遵循 maven 项目创建示例来创建项目。 现在,将 spring 依赖项与javax.mail一起导入。

pom.xml

<properties>
	<spring.version>5.2.0.RELEASE</spring.version>
	<email.version>1.16.18</email.version>
</properties>

<!-- Spring Context Support -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>${spring.version}</version>
</dependency>

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>${email.version}</version>
</dependency>

2. JavaMailSender和电子邮件模板

2.1. Java 配置

给出了JavaMailSender的 Java 配置,该配置已配置为使用 Gmail SMTP 设置,并且我们配置了示例电子邮件模板,该模板已预先配置了发件人/收件人电子邮件和电子邮件文本。

您可以根据需要自定义配置。

EmailConfig.java

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
public class EmailConfig 
{
	@Bean
	public JavaMailSender getJavaMailSender() 
	{
	    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
	    mailSender.setHost("smtp.gmail.com");
	    mailSender.setPort(25);

	    mailSender.setUsername("admin@gmail.com");
	    mailSender.setPassword("password");

	    Properties props = mailSender.getJavaMailProperties();
	    props.put("mail.transport.protocol", "smtp");
	    props.put("mail.smtp.auth", "true");
	    props.put("mail.smtp.starttls.enable", "true");
	    props.put("mail.debug", "true");

	    return mailSender;
	}

	@Bean
	public SimpleMailMessage emailTemplate()
	{
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("somebody@gmail.com");
		message.setFrom("admin@gmail.com");
	    message.setText("FATAL - Application crash. Save your job !!");
	    return message;
	}
}

2.2. XML 配置

在 Spring 上下文文件中,我们将创建一个通用的邮件发件人服务,该服务能够使用 gmail 的 smtp 服务器发送 HTTP 消息。

另外,我们正在制作一个预配置的消息,该消息可以即时实例化并用于发送消息。

applicationContext.xml

<beans>

    <context:component-scan base-package="com.howtodoinjava" />    

    <!-- SET default mail properties -->
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	  	<property name="host" value="smtp.gmail.com"/>
	  	<property name="port" value="25"/>
	  	<property name="username" value="admin@gmail.com"/>
	 	<property name="password" value="password"/>
	  	<property name="javaMailProperties">
			<props>
			    <prop key="mail.transport.protocol">smtp</prop>
			    <prop key="mail.smtp.auth">true</prop>
			    <prop key="mail.smtp.starttls.enable">true</prop>
			    <prop key="mail.debug">true</prop>
			</props>
  		</property>
    </bean>

    <!-- We can have some pre-configured messagess also which are ready to send -->

    <bean id="preConfiguredMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="to" value="somebody@gmail.com"></property>
		<property name="from" value="admin@gmail.com"></property>
  		<property name="subject" value="FATAL - Application crash. Save your job !!"/>
    </bean>
</beans>

3. 发送电子邮件

此类使用applicationContext.xml文件中配置的 bean,并使用它们发送消息。

EmailService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

@Service("emailService")
public class EmailService 
{
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SimpleMailMessage preConfiguredMessage;

    /**
     * This method will send compose and send the message 
     * */
    public void sendMail(String to, String subject, String body) 
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        mailSender.send(message);
    }

    /**
     * This method will send a pre-configured message
     * */
    public void sendPreConfiguredMail(String message) 
    {
        SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}

4. 带有附件和内联资源的电子邮件

4.1. 电子邮件附件

要使用电子邮件附加文件,请使用MimeMessageHelper将文件附加MimeMessage

Attach file

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(body);

            FileSystemResource file = new FileSystemResource(new File(fileToAttach));
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.addAttachment("logo.jpg", file);
        }
    };

    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

4.2. 内联资源

有时,我们可能希望在电子邮件正文中附加内嵌资源,例如内嵌图像。

通过使用指定的Content-ID将内联资源添加到MimeMessage。 确保首先添加文本,然后添加资源。 如果您正相反进行操作,则此操作无效。

Inline image

public void sendMailWithInlineResources(String to, String subject, String fileToAttach) 
{
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        public void prepare(MimeMessage mimeMessage) throws Exception 
        {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
            mimeMessage.setSubject(subject);

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            helper.setText("<html><body><img src='cid:identifier1234'></body></html>", true);

            FileSystemResource res = new FileSystemResource(new File(fileToAttach));
            helper.addInline("identifier1234", res);
        }
    };

    try {
        mailSender.send(preparator);
    }
    catch (MailException ex) {
        // simply log it and go on...
        System.err.println(ex.getMessage());
    }
}

5. 演示

是时候测试 spring 邮件发送程序代码了。 我正在从测试代码发送两条消息。 一个实例化并由测试类本身组成,另一个是来自applicationContext.xml文件的预配置消息。

SpringEmailTest.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringEmailTest 
{
	public static void main(String[] args) 
    {
        //Create the application context
        ApplicationContext context = new FileSystemXmlApplicationContext
        			("classpath:com/howtodoinjava/core/email/applicationContext.xml");

        //Get the mailer instance
        EmailService mailer = (EmailService) context.getBean("emailService");

        //Send a composed mail
        mailer.sendMail("somebody@gmail.com", "Test Subject", "Testing body");

        //Send a pre-configured mail
        mailer.sendPreConfiguredMail("Exception occurred everywhere.. where are you ????");
    }
}

上面的通话将发送电子邮件。

学习愉快!