Java Mail

2017/04/02 JavaSE

JavaMail

协议

  • SMTP 发送
  • POP3 接收
  • IMAP 发送和接收
public class JavaMail {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");// 邮件服务器地址
        properties.setProperty("mail.smtp.auth", "true");// 是否需要身份认证

        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {// 认证信息
                return new PasswordAuthentication("username", "password");
            }
        };
        Session session = Session.getDefaultInstance(properties, authenticator);// 获取session

        Transport transport = null;
        try {
            transport = session.getTransport();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            return;
        }


        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom("from@qq.com");// 发送人
            message.setRecipients(Message.RecipientType.TO, "to@qq.com");// 收件人
            message.setRecipients(Message.RecipientType.CC, "cc@qq.com");// 抄送
            message.setRecipients(Message.RecipientType.BCC, "bcc@qq.com");// 密送
            message.setSubject("标题");// 标题
            // 内容
            // message.setContent("你好", "text/html;charset=UTF-8");

            MimeMultipart mimeMultipart = new MimeMultipart();
            // 文本内容
            MimeBodyPart part = new MimeBodyPart();
            part.setContent("你好", "text/html;charset=UTF-8");
            mimeMultipart.addBodyPart(part);
            // 附件
            MimeBodyPart part1 = new MimeBodyPart();
            try {
                part1.attachFile(new File("附件.zip"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                part1.setFileName(MimeUtility.encodeText("附件"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            mimeMultipart.addBodyPart(part1);

            message.setContent(mimeMultipart);
        } catch (MessagingException e) {
            e.printStackTrace();
            return;
        }

        try {
            transport.send(message);// 发送
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

使用Spring发送Email

配置Spring发送邮件

配置邮件发送器

Spring的MailSender接口是Spring Email抽象API的核心组件。它把Email发送给邮件服务器,由服务器进行邮件投递

spring-mail

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

@Bean
public JavaMailSenderImpl mailSender(Environment env) {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(env.getProperty("mailserver.host"));
    mailSender.setPort(Integer.parseInt(env.getProperty("mailserver.port")));
    mailSender.setUsername(env.getProperty("mailserver.username"));
    mailSender.setPassword(env.getProperty("mailserver.password"));
    return mailSender;
}

或者直接使用JNDI配置:

@Bean
public JndiObjectFactoryBean session() {
    JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
    jndiObjectFactoryBean.setJndiName("mail/Session");
    jndiObjectFactoryBean.setProxyInterface(javax.mail.Session.class);
    jndiObjectFactoryBean.setResourceRef(true);
    return jndiObjectFactoryBean;
}
@Bean
public MailSender mailSender(Session session) {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setSession(session);
    return javaMailSender;
}
<jee:jndi-lookup jndi-name="mail/Session" id="mailSession" resource-ref="true"/>

装配和使用邮件发送器

private JavaMailSender mailSender;
@Autowired
public SpitterMailServiceImpl(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}
@Override
public void sendSimpleSpittleEmail(String to, Spittle spittle) {
    SimpleMailMessage message = new SimpleMailMessage();
    String spitterName = spittle.getSpitter().getFullName();
    message.setFrom("noreply@spitter.com");
    message.setTo(to);
    message.setSubject("New spittle from " + spitterName);
    message.setText(spitterName + " says: " + spittle.getText());
    mailSender.send(message);
}

构建丰富内容的Email消息

添加附件

@Override
public void sendSpittleEmailWithAttachment(String to, Spittle spittle) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    String spitterName = spittle.getSpitter().getFullName();
    helper.setFrom("noreply@spitter.com");
    helper.setTo(to);
    helper.setSubject("New spittle from " + spitterName);
    helper.setText(spitterName + " says: " + spittle.getText());
    ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.png");
    helper.addAttachment("Coupon.png", couponImage);
    mailSender.send(message);
}

发送富文本内容的Email

helper.setText("<h1>Hello</h1>", true);
helper.addInline("Logo", couponImage);

使用模板生成Email

使用Velocity构建Email消息

@deprecated as of Spring 4.3, in favor of FreeMarker

@Bean
public VelocityEngineFactoryBean velocityEngineFactoryBean() {
    VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean();
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "class");
    properties.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    return velocityEngineFactoryBean;
}
@Autowired
private VelocityEngine velocityEngine;

public void sendRichTextMailWithVelocity(String spitterName, Spittle spittle) {
    Map<String, Object> map = new HashMap<>();
    map.put("spitterName", spitterName);
    map.put("spitterText", spittle.getText());
    String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "emailTemplate.vm", "UTF-8", map);
    // ...
}

使用Thymeleaf构建Email消息

@Autowired
private SpringTemplateEngine springTemplateEngine;// 参考springmvc的thymeleaf配置
public void sendRichTextMailWithThymeLeaf(String spitterName, Spittle spittle) {
    Context context = new Context();
    context.setVariable("spitterName", spitterName);
    context.setVariable("spitterText", spittle.getText());
    String emailText = springTemplateEngine.process("emailTemplate.html", context);
}
@Bean // 除ServletContextTemplateResolver外配置另一个
public ClassLoaderTemplateResolver templateResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setPrefix("mail/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setOrder(1);// 另一个设值为2
    return templateResolver;
}
@Bean
public TemplateResolver servletTemplateResolver() {
    TemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setOrder(2);
    return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(TemplateResolver templateResolver, Set<ITemplateResolver> viewResolvers) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);
    templateEngine.setTemplateResolvers(viewResolvers);
    return templateEngine;
}

以上概念总结于传智播客JavaWeb课程

Search

    Post Directory