spring中配置邮件发送服务

spring中配置邮件发送服务 
参考:https://juejin.im/entry/5898277b2f301e00696bea1d

需要的邮件jar包

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.10.RELEASE</version>
</dependency>

1、在applicationContent.xml中配置邮件相关参数

<!-- 加载systemInfo.properties属性文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />  
    </bean> 

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:systemInfo.properties</value>
            </list>
        </property>
    </bean>

    <!-- 邮件发送   -->    
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host"     value="${sys.mail.host}" />
        <property name="username" value="${sys.mail.sysEmailAddress}" />
        <property name="password" value="${sys.mail.password}" />
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${sys.mail.smtp.auth}</prop>
                <prop key="mail.smtp.timeout">${sys.mail.smtp.timeout}</prop>    
                <prop key="mail.smtp.port">${sys.mail.smtp.port}</prop>    
            </props>
        </property>
    </bean>

2、systemInfo.properties属性文件

sys.mail.protocol=smtp
sys.mail.host=smtp.163.com
sys.mail.sysEmailAddress=***@163.com
sys.mail.password=***  #在163邮箱中设置授权码
sys.mail.smtp.auth=true
sys.mail.smtp.timeout=25000
sys.mail.smtp.port=25

3、EmailSendManager.java接口

package com.mdl.monitor.services;

import javax.mail.MessagingException;

import com.mdl.monitor.bean.SimpleEmail;

public interface EmailSendManager {
    /**
     * 发送简单邮件
     * 
     * @param simpleEmail
     *            简单邮件详情
     * @throws MessagingException
     */
    void sendEmail(SimpleEmail simpleEmail) throws MessagingException;

}
  •  

4、EmailSendManagerImpl.java实现类

package com.mdl.monitor.services.impl;

import java.io.File;
import java.util.Map;
import java.util.Set;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.mdl.monitor.bean.SimpleEmail;
import com.mdl.monitor.services.EmailSendManager;

@Component("simpleEmailSendManagerImpl")
public class EmailSendManagerImpl implements EmailSendManager {

    @Value("${sys.mail.sysEmailAddress}")
    private String from; // 发送者

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendEmail(SimpleEmail simpleEmail) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, simpleEmail.isAttachment());

        /**
         * 添加发送者
         */
        helper.setFrom(from);

        Set<String> toSet = simpleEmail.getToSet();
        /**
         * 添加接收者
         */
        helper.setTo(toSet.toArray(new String[toSet.size()]));

        /**
         * 添加主题
         */
        helper.setSubject(simpleEmail.getSubject());
        /**
         * 添加正文
         */
        helper.setText(simpleEmail.getContent(), simpleEmail.isHtml());

        /**
         * 添加附件
         */
        if (simpleEmail.isAttachment()) {
            Map<String, File> attachments = simpleEmail.getAttachments();

            if (attachments != null) {
                for (Map.Entry<String, File> attach : attachments.entrySet()) {
                    helper.addAttachment(attach.getKey(), attach.getValue());
                }
            }

        }

        mailSender.send(message); // 发送
    }

}
  •  

5、SimpleEmail.java实体类

package com.mdl.monitor.bean;

import java.io.File;
import java.util.Map;
import java.util.Set;

public class SimpleEmail {
    private Set<String> toSet; // 收件人
    private String subject; // 主题
    private String content; // 正文
    private boolean isHtml; // 正文是否是HTML
    private Map<String, File> attachments; // 附件路径
    private boolean isAttachment; // 是否有附件

    public Set<String> getToSet() {
        return toSet;
    }

    public void setToSet(Set<String> toSet) {
        this.toSet = toSet;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public boolean isHtml() {
        return isHtml;
    }

    public void setHtml(boolean isHtml) {
        this.isHtml = isHtml;
    }

    public Map<String, File> getAttachments() {
        return attachments;
    }

    public void setAttachments(Map<String, File> attachments) {
        this.attachments = attachments;
    }

    public boolean isAttachment() {
        return isAttachment;
    }

    public void setAttachment(boolean isAttachment) {
        this.isAttachment = isAttachment;
    }

}

6、测试类TestSendEmail.java

package com.mdl.monitor.test;

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

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mdl.monitor.bean.SimpleEmail;
import com.mdl.monitor.services.EmailSendManager;
import com.mdl.monitor.util.FreeMarkerUtils;

import freemarker.template.TemplateException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
public class TestSendEmail {

    @Resource(name = "simpleEmailSendManagerImpl")
    private EmailSendManager emailSendManager;

    /**
     * 发送HTML格式的邮件
     * 
     * @throws MessagingException
     * @throws Exception 
     * @throws TemplateException 
     */
    @Test
    public void sendHTMLEmail() throws MessagingException, TemplateException, Exception {
        SimpleEmail simpleEmail = new SimpleEmail();
        simpleEmail.setSubject("这里是主题");

        Set<String> receivers = new HashSet<>();
        receivers.add("[email protected]");
        simpleEmail.setToSet(receivers);
        simpleEmail.setHtml(true);
        simpleEmail.setContent("<html><head><meta http-equiv=\"Content-Type\" "
        + "content=\"text/html; charset=UTF-8\"></head>"
        + "<body><div align=\"center\" style=\"color:#F00\">"
        + "<h2>测试在Spring中发送带HTML格式的邮件</h2></div></body></html>");
        simpleEmail.setAttachment(false);
        emailSendManager.sendEmail(simpleEmail);
    }


/**
   * 发送简单邮件
   * @throws MessagingException
   */
  @Test
  public void sendSimpleEmail() throws MessagingException {
    SimpleEmail simpleEmail = new SimpleEmail();
    simpleEmail.setSubject("测试在Spring中发送邮件");

    Set<String> receivers = new HashSet<>();
    receivers.add("[email protected]");
    simpleEmail.setToSet(receivers);

    simpleEmail.setHtml(false);
    simpleEmail.setContent("Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、"
        + "事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。");

    simpleEmail.setAttachment(false);

    emailSendManager.sendEmail(simpleEmail);
  }
}

猜你喜欢

转载自blog.csdn.net/wsh596823919/article/details/81164261