征服Spring唯爱Spring

Spring mail 邮件服务

2017-08-22  本文已影响35人  ChinaXieShuai

业务发展的过程中,需要对业务的关键点进行监控,当监控到业务出现异常的时候,大多数时候希望以邮件的方式通知 干系人。Spring为我们提供了 发邮件 的工具类与接口

applicationContext.xml 文件中添加:

<context:property-placeholder location="classpath*:mailUrl.properties" />
<!--email的配置-->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}" />
        <property name="username" value="${mail.username}" />
        <property name="password" value="${mail.password}" />
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.from">${mail.username}</prop>
                <prop key="mail.transport.protocol">smtps</prop>
            </props>
        </property>
    </bean>

mailUrl.properties 文件的内容:

mail.host=someonehost
mail.username=someoneMailUserName
mail.password=someoneMailPassWord

此时,spring中mail配置已经做完了,只需要创建一个service进行发送邮件就行

NotifyService 的内容为:

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.Map;

/**
 * Created by shuai
 */
@Service
public class NotifyService {

    private static Logger logger = LoggerFactory.getLogger(NotifyService.class);

    @Autowired
    private JavaMailSender mailSender;

    public boolean notifyEmail(MailVo mail) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 发送人
            if (null != mail.getMsgFrom()) {
                helper.setFrom(mail.getMsgFrom());
            }
            // 密送
            if (null != mail.getBcc()) {
                helper.setBcc(StringUtils.split(mail.getBcc(), ","));
            }
            // 抄送
            if (null != mail.getCc()) {
                helper.setCc(StringUtils.split(mail.getCc(), ","));
            }
            // 收件人
            if (null != mail.getMsgTo()) {
                helper.setTo(StringUtils.split(mail.getMsgTo(), ","));
            }
            // 邮件主题
            helper.setSubject(mail.getSubject());
            // 邮件的内容
            helper.setText(mail.getText(), true);
            // 附件
            if (null != mail.getAttachmentList()) {
                for (Map.Entry<String, Object> entry : mail.getAttachmentList().entrySet()) {
                    if (entry.getValue() instanceof File) {
                        helper.addAttachment(MimeUtility.encodeText(entry.getKey()), (File) entry.getValue());
                    }
                }
            }
            // 图片
            if (null != mail.getImagesList()) {
                for (Map.Entry<String, Object> entry : mail.getImagesList().entrySet()) {
                    if (entry.getValue() instanceof File) {
                        helper.addInline(entry.getKey(), (File) entry.getValue());
                    }
                }
            }
            // 发送邮件
            mailSender.send(mimeMessage);
            return true;
        } catch (Exception e) {
            logger.error("notify email error. informetion{}, 异常信息{}", mail, e);
            return false;
        }
    }
}

mailVo 文件的内容为:

import java.io.Serializable;
import java.util.Map;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
/**
 * Created by shuai
 */
public class MailVo implements Serializable {

    private static final long serialVersionUID = 1L;
    // ID
    private long id;
    // 发送人
    private String msgFrom;
    // 收件人
    private String msgTo;
    // 密送
    private String bcc;
    // 抄送
    private String cc;
    // 主题
    private String subject;
    // 消息
    private String text;
    // 附件ID
    private String fileIds;
    // 图片ID
    private String imgIds;
    // 附件
    private Map<String, Object> attachmentList;
    // 图片
    private Map<String, Object> imagesList;
    // 状态
    private String status;
    // 响应消息
    private String resInfo;

    // getAndSetMethod()...
      
    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }
}

此时只需要调用 NotifyService 中的方法就行了。

MailVo mail = new MailVo();
mail.setMsgTo("someOneEmailAddress");
mail.setText("这是一个测试邮件发送的内容");
mail.setSubject("测试的邮件Title");
// 发送邮件
notifyService.notifyEmail(mail);
上一篇下一篇

猜你喜欢

热点阅读