[Spring集成]-配置Spring发邮件

1.引言:

毫无疑问, Email 已经成为常见的通信形式,取代了很多传统的通信方式,如邮政邮件、电话,在一定程度上也替代了面对面的交流。 Email 能够提供了与第 17 章中所讨论的异步消息相同的收益,只不过发送者和接收者都是实际的人而已。只要你在邮件客户端上点击 “ 发送 ” 按钮,就可以转移到其他的任务中了,因为我们知道接收者最终将会收到并阅读(希望如此)你的 Email 。但是, Email 的发送者不一定是实际的人。有时候, Email 消息是由应用程序发送给用户的。有可能是电子商务网站上的订单确认邮件,也有可能是银行账户某项交易的自动提醒。不管邮件的主题是什么,我们都可能需要开发发送 Email 消息的应用程序。幸好,在这个方面, Spring 会为我们提供帮助。

2.配置Spring发送邮件:

Spring Email 抽象的核心是 MailSender 接口。顾名思义, MailSender 的实现能够通过连接Email 服务器实现邮件发送的功能,如下图所示:


Spring自带了一个MailSender的实现也就是JavaMailSenderImpl,他会使用JavaMail API来发送Email.Spring应用在发送Email之前,我们必须要将JavaMailSenderImpl装配为Spring应用上下文中的一个bean.

2.1配置邮件发送器

按照最简单的形式,我们只需在 @Bean 方法中使用几行代码就能将 JavaMailSenderImpl 配置

为一个 bean :然后设置JavaMailSenderImpl的服务器地址,端口号,用户名,密码,但这种方式配置容易出错,我们采用第二种方式:配置javax.mail.MailSession.这样的话就没有必要配置JavaMailSenderImpl配置详细的服务器细节了。我们可以配置它使用JNDI中已就绪的MailSession.

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;


@Configuration
@ComponentScan("com")
public class MailConfig {

  @Bean 
  public Session session(){
	  	Properties pro = new Properties();
		pro.setProperty("mail.host", "smtp.sina.cn");
		pro.setProperty("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("18896658738@sina.cn", "邮箱密码!");
			}
		};
		Session session = Session.getInstance(pro, auth);
		return session;
  }
	
	
  @Bean
  public JavaMailSenderImpl mailSender(Session session) {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setSession(session);
    return mailSender;
  }  
  
}

2.2装配和使用邮件发送器

邮件发送器已经配置完成,现在需要将其装配到使用它的bean中了。在应用程序中,最适合发送Email的是JinNangEmailServiceImpl类。这个类有一个mailSender属性,它使用了@Autowired注解:

当Spring将SpitterEmailServiceImpl创建为一个bean的时候,他将查找实现了MailSender的bean,这样的bean可以装配到mailSender属性中。他将会找到我们在前面配置额mailSender Bean并使用它。mailSenderBean装配完成后,我们就可以构建和发送Email了。有一点,我们使用邮件发送器发送邮件,邮件的发送者应和前面配置的Session中的用户名一致。

接口JinNangMailService

import javax.mail.MessagingException;

import com.domain.JinNang;


public interface JinNangMailService {

  public abstract void sendSimpleSpittleEmail(String to, JinNang spittle);

  public abstract void sendSpittleEmailWithAttachment(String to, JinNang spittle)
      throws MessagingException;

}

JinNangService接口实现类:

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.domain.JinNang;

@Component
public class JinNangMailServiceImpl implements JinNangMailService {

  private JavaMailSender mailSender;

  @Autowired
  public JinNangMailServiceImpl(JavaMailSender mailSender) {
    this.mailSender = mailSender;
  }

  @Override
  public void sendSimpleSpittleEmail(String to, JinNang jinnang) {
    SimpleMailMessage message = new SimpleMailMessage();
    String people = jinnang.getPeople();
    message.setFrom("18896658738@sina.cn");
    message.setTo(to);
    message.setSubject("New Jinnang from " + people);
    message.setText(people + " says: " + jinnang.getJice());
    mailSender.send(message);
  }

  /* (non-Javadoc)
   * @see spittr.email.SpitterMailService#sendSpittleEmailWithAttachment(java.lang.String, spittr.domain.Spittle)
   */
  @Override
  public void sendSpittleEmailWithAttachment(String to, JinNang jinnang) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    String people = jinnang.getPeople();
    helper.setFrom("18896658738@sina.cn");
    helper.setTo(to);
    helper.setSubject("New jinnang from " + people);
    helper.setText(people + " says: " + jinnang.getJice());
    ClassPathResource couponImage = new ClassPathResource("collateral/coupon.jpg");
    
    helper.addAttachment("Coupon.png", couponImage);
    mailSender.send(message);
  }

}

sendSimpleSpittleEmail() 方法所做的第一件事就是构造 SimpleMailMessage 实例。正如其名称所示,这个对象可以很便捷地发送 Email 消息。接下来,将设置消息的细节。通过邮件消息的 setFrom() 和 setTo() 方法指定了 Email 的发送者和接收者。在通过 setSubject() 方法设置完主题后,虚拟的 “ 信封 ” 已经完成了。剩下的就是调用 setText() 方法来设置消息的内容。最后一步是将消息传递给邮件发送器的 send() 方法,这样邮件就发送出去了。

2.3构造丰富内容的Email消息-添加附件

如果发送带有附件的 Email ,关键技巧是创建 multipart 类型的消息 ——Email 由多个部分组成,其中一部分是 Email 体,其他部分是附件。对于发送附件这样的需求来说, SimpleMailMessage 过于简单了。为了发送 multipart 类型的Email ,你需要创建一个 MIME ( Multipurpose Internet Mail Extensions )的消息,我们可以从邮件发送器的 createMimeMessage() 方法开始:就这样,我们已经有了要使用的 MIME 消息。看起来,我们所需要做的就是指定收件人和发件人地址、主题、一些内容以及一个附件。尽管确实是这样,但并不是你想的那么简单。 javax.mail.internet.MimeMessage 本身的 API 有些笨重。好消息是, Spring 提供的 MimeMessageHelper 可以帮助我们。为了使用 MimeMessageHelper ,我们需要实例化它并将 MimeMessage 传给其构造器:构造方法的第二个参数,在这里是个布尔值 true ,表明这个消息是 multipart 类型的。得到了 MimeMessageHelper 实例后,我们就可以组装 Email 消息了。这里最主要区别在于使用helper 的方法来指定 Email 细节,而不再是设置消息对象:

@Override
  public void sendSpittleEmailWithAttachment(String to, JinNang jinnang) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    String people = jinnang.getPeople();
    helper.setFrom("18896658738@sina.cn");
    helper.setTo(to);
    helper.setSubject("New jinnang from " + people);
    helper.setText(people + " says: " + jinnang.getJice());
    ClassPathResource couponImage = new ClassPathResource("collateral/coupon.jpg");
    
    helper.addAttachment("Coupon.png", couponImage);
    mailSender.send(message);
  }

2.4编写测试类:

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;


@Configuration
@ComponentScan("com")
public class MailConfig {

  @Bean 
  public Session session(){
	  	Properties pro = new Properties();
		pro.setProperty("mail.host", "smtp.sina.cn");
		pro.setProperty("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("18896658738@sina.cn", "邮箱密码");
			}
		};
		Session session = Session.getInstance(pro, auth);
		return session;
  }
	
	
  @Bean
  public JavaMailSenderImpl mailSender(Session session) {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setSession(session);
    return mailSender;
  }  
  
}

运行截图:



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值