使用 Spring JavaMailSender 发送电子邮件

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(374)   2023-06-26 07:54:18

学习在 Spring 中发送电子邮件 提供 JavaMailSender 接口。这是 通过 Gmail SMTP 服务器 发送电子邮件。我们将使用 javax.mail maven 依赖项来发送电子邮件,同时在实现 JavaMailSender 接口。

1.专家

按照maven project creation example创建一个新项目.现在将 Spring 依赖项与 javax.mail 一起导入。

<properties>
  <spring.version>5.3.23</spring.version>
  <email.version>1.6.2</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>

如果我们使用 Spring boot,那么我们可以通过简单地包含 spring 来帮助其自动配置功能-boot-starter-mail 启动器。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

入门模板将传递性地导入项目中所需的 jar。

[INFO] \- org.springframework.boot:spring-boot-starter-mail:jar:2.1.2.RELEASE:compile
[INFO]    +- org.springframework:spring-context-support:jar:5.1.4.RELEASE:compile
[INFO]    |  \- org.springframework:spring-beans:jar:5.1.4.RELEASE:compile
[INFO]    \- com.sun.mail:javax.mail:jar:1.6.2:compile
[INFO]       \- javax.activation:activation:jar:1.1:compile

2. 使用 JavaMailSender 发送 SimpleMailMessage

2.1.配置 JavaMailSenderImpl 和电子邮件模板

给定的是 JavaMailSender 的 Java 配置,它已被配置为使用 Gmail SMTP 设置,我们已经配置了一个示例电子邮件模板,该模板预先配置了发件人/收件人电子邮件和电子邮件文本。

我们可以根据需要进一步自定义配置。

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()
	{
	    JavaMailSender 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.发送电子邮件

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

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 a new message
     * */
    public void sendNewMail(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);
    }
}

3. 使用 JavaMailSenderMimeMessagePreparator

使用 JavaMailSender 接口的推荐方法是 MimeMessagePreparator 机制并使用 MimeMessageHelper 来填充消息。

@Autowired
private JavaMailSender mailSender;

public void sendMail() {  

	MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {  
		public void prepare(MimeMessage mimeMessage) throws Exception {  
			MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			message.setFrom("me@mail.com");
			message.setTo("you@mail.com");
			message.setSubject("Mail subject");
			message.setText("some text <img src='cid:logo'>", true);
			message.addInline("logo", new ClassPathResource("img/logo.gif"));
			message.addAttachment("myDocument.pdf", new ClassPathResource("uploads/document.pdf"));
		}  
	};  

	mailSender.send(messagePreparator);  
}

4.邮件属性

我们可以将邮件属性配置到 application.properties 文件中,并使用 @Value 注释进行注入。

spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=admin@gmail.com
spring.mail.password=password

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.starttls.enable=true

#Timeouts
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

如果您打算使用 Amazon SES 发送电子邮件,那么您可以使用以下属性:

spring.mail.host=email-smtp.us-west-2.amazonaws.com
spring.mail.username=username
spring.mail.password=password

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

5. 电子邮件附件和内联资源

发送仅包含 HTML、没有附件或内联元素的简单邮件消息很容易。但是,内联元素和附件仍然是电子邮件客户端之间的主要兼容性问题

请使用适当的 MULTIPART_MODE 并在将代码投入生产之前彻底测试代码。

5.1.电邮附件

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

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());
    }
}

5.2.内联资源

有时,我们可能希望在电子邮件正文中附加内联资源,例如内联图像。使用指定的内容 ID 将内联资源添加到 MimeMessage。请务必先添加文本,然后再添加资源。如果您以相反的方式进行操作,则它不起作用。

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());
    }
}

6.演示

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

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 ????");
    }
}

上面的调用将发送电子邮件。

快乐学习!!

标签2: Spring Core Java Mail
地址:https://www.cundage.com/article/send-email-with-spring-javamailsenderimpl-example.html

相关阅读

学习在 Spring 中发送电子邮件 提供 JavaMailSender 接口。这是 通过 Gmail SMTP 服务器 发送电子邮件。我们将使用 javax.mail maven 依赖项来发送...
Gmail 用户可以使用 Gmail 的 SMTP 服务器 smtp.gmail.com 从他们的 Spring Boot 应用程序发送电子邮件。为此,让我们在应用程序中进行一些设置: 在app...
Spring Boot 发送电子邮件教程展示了如何在 Spring Boot 应用程序中发送电子邮件。我们使用 Mailtrap 服务。 春天 是一个流行的 Java 应用程序框架,弹簧贴 是 ...
异常处理是任何 Java 应用程序的一个非常重要的特性。每个好的开源框架都允许以这样一种方式编写异常处理程序,以便我们可以将它们与我们的应用程序代码分开。好吧,Spring 框架 还允许我们使用...
Java 配置示例在 @EnableWebSecurity 注释和 WebSecurityConfigurerAdapter 类的帮助下启用 spring 安全。此示例构建在 spring we...
我们知道,如果我们必须通过 Java 代码向某人发送邮件,我们需要访问某些邮件服务器凭据。如果我们无权访问这些凭据,Google 会通过我们的 Gmail 帐户提供对 Gmail SMTP 服务...
如果您正在开发基于 spring 的 Web 应用程序,该应用程序需要在 web.xml 文件中使用 org.springframework.web.context.ContextLoaderL...
Spring Boot @ConfigurationProperties 教程展示了如何在 Spring Boot 应用程序中使用 @ConfigurationProperties 将属性绑定到...
在 Spring 框架中,在配置文件中声明 bean 依赖关系是一个值得遵循的好习惯,因此 Spring 容器能够自动装配协作 bean 之间的关系。这意味着可以通过检查 BeanFactory...
Spring 为基于 cron expression 使用 $ 的任务调度和异步方法执行提供了出色的支持$$ 注释。 @Scheduled 注释可以与触发器元数据一起添加到方法中。 在这篇文章中...