首页 > Java > 如何利用模板发送邮件

如何利用模板发送邮件

目前web应用很多时候都需要像用户发送邮件,尤其是在我们注册的时候,其实这些邮件很多时候内容都是类似的,仅仅是一些有户名等不同,那么我们是否可以利用一个模板呢,模板里面有一些占位符,当我们要发送邮件的时候,仅仅把这些占位符做一替换就行了呢?答案肯定是可以的,请看下面的例子程序:

1. 邮件模板mailTemplate.xml


<?xml version="1.0" encoding="UTF-8"?>
<email>
    <ProjectMail>
        <subject id="ProjectSubject"> <![CDATA[Hello%toUsername%]]></subject>
        <content id="ProjectMailBody">
            <![CDATA[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
            <HTML>
                <HEAD>
                    <META http-equiv=Content-Type content="text/html; charset=UTF-8">
                    <META content="MSHTML 6.00.6000.17063" name=GENERATOR>
                    <STYLE>
                        TABLE {
                            MARGIN-LEFT: 20px;
                        }

                        TD {
                            border: 1px solid #CBCBCB;
                        }

                        .dataString {
                            text-align:left;
                            padding-left:3px;
                        }

                        .tableTittle{
                            background-color: #FF9900;
                        }
                    </STYLE>
                </HEAD>

                <BODY bgColor=#ffffff>
                    <DIV>
                        <FONT face=Arial size=2></FONT>
                    </DIV>
                    <DIV>
                        <FONT face=Arial size=2>
                            Hi %name%,
                        </FONT>
                    </DIV>

                    <br>

                    <DIV>
                        <FONT face=Arial size=2>
                            欢迎注册
                        </FONT>
                    </DIV>

                    <br>

                    <DIV>
                        <FONT face=Arial size=2>
                            该邮件是系统自动发出,请不要直接回复,谢谢
                        </FONT>
                    </DIV>

                    <br>

                    <table width="800" border="1" cellspacing="0" cellpadding="0">
                        <tr class="tableTittle">
                            <th width="25%">
                                <font size="2" face="Arial" class="dataString" >
                                   <p align="center">
                                       Name
                                    </p>
                                </font>
                            </th>

                            <th width="25%">
                                <font size="2" face="Arial" class="dataString" >
                                    <p align="center">
                                        Date and time
                                    </p>
                                 </font>
                            </th>
                        </tr>

                        <#listItems></#listItems>

                    </table>

                    <br>

                    <DIV>
                        <FONT face=Arial size=2></FONT>
                    </DIV>
                    <DIV>
                        <FONT face=Arial size=2>
                            Kind regards,
                        </FONT>
                    </DIV>

                    <DIV>
                        <FONT face=Arial size=2>
                            Bridge
                        </FONT>
                    </DIV>

                ]]>

        </content>
    </ProjectMail>
</email>

2. Java代码:


@Service("mailService")
public class MailServiceImpl implements MailService {

    private static final Logger LOG = LoggerFactory.getLogger(MailServiceImpl.class);

    private static final String DO_INVOICE_ITMES = "<#listItems></#listItems>";

    private static final String NAME = "%name%";

    @Override
    public void sendMail() {

        List<String> mailCCList = new ArrayList<String>();

        String attachmentPath = null;

        Map<String, String> mail = buildMail(receiverName);

        String emailContent = mail.get("mailContent");

        String subject = mail.get("emailSubject");

        toSendMail(receiverMailAddress, mailCCList, emailContent, subject, attachmentPath, attachmentName);

    }

    private void toSendMail(String toAddress, List<String> mailCCList, String emailContent, String subject, String attachmentPath, String attachmentName) {

        Properties props = new Properties();

// Set the attribute of mail server

        props.put("mail.smtp.host", MAIL_SERVER_HOST));

// Need to be authorized, such ability through validation (must have this one)

        props.put("mail.smtp.auth", "true");

// Build a session with props objects

        Session session = Session.getDefaultInstance(props);

// Using the session as parameters define the message object

        MimeMessage message = new MimeMessage(session);

        Transport transport = null;

        try {

// Load the sender's address

            message.setFrom(new InternetAddress(MAIL_ADDRESS);

// Load the recipient address

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

            if (StringUtil.isNotEmpty(mailCCList)) {

                InternetAddress[] to_mail = new InternetAddress[mailCCList.size()];

                for (int i = 0; i < mailCCList.size(); i++) {

                    to_mail[i] = new InternetAddress(mailCCList.get(i));

                }

                message.addRecipients(Message.RecipientType.CC, to_mail);

            }

// Load the subject

            message.setSubject(subject);

// Add mail each part to the multipart, including the text content

// and accessories

            MimeMultipart multipart = new MimeMultipart();

// Set the HTML content of the message

            BodyPart contentPart = new MimeBodyPart();

// To set the content and format/encoding of BodyPart

            contentPart.setContent(emailContent, "text/html;charset=UTF-8");

            multipart.setSubType("related");

            multipart.addBodyPart(contentPart);

// Add attachment

            if (!StringUtil.isNullOrEmpty(attachmentName)) {

                contentPart = new MimeBodyPart();

                DataSource source = new FileDataSource(attachmentPath);

// Add attachment's content

                contentPart.setDataHandler(new DataHandler(source));

// Add attachment's title

                contentPart.setFileName(attachmentName);

                multipart.addBodyPart(contentPart);

            }

// Add multipart object to the message

            message.setContent(multipart);

// Save the mail

            message.saveChanges();

            transport = session.getTransport("smtp");

// Connect the mail server

            transport.connect(MAIL_SERVER_HOST, MAIL_SERVER_USERNAME, MAIL_SERVER_PASSWORD);

// Send mail

            transport.sendMessage(message, message.getAllRecipients());

            LOG.info("Send mail to: " + toAddress + ",success");

        } catch (AddressException e) {

            LOG.error(e);

        } catch (NoSuchProviderException e) {

            LOG.error(e);

        } catch (MessagingException e) {

            LOG.error(e);

        } finally {

            try {

                if (null != transport) {

                    transport.close();

                }

            } catch (MessagingException e) {

                LOG.error(e);

            }

        }

    }

    private Map<String, String> buildMail(String receiverName) {

        StringBuilder itemsBuilder = new StringBuilder();

        Element emailTemplateRoot = getXMLRootElement("mailTemplate.xml");

        String emailSubject = emailTemplateRoot.selectSingleNode("//*[@id='ProjectSubject']").getText().replace(TOUSERNAME, receiverName.toUpperCase());

        StringBuilder content = new StringBuilder();

        String mailTemplateContent = emailTemplateRoot.selectSingleNode("//*[@id='ProjectMailBody']").getText();

        mailTemplateContent = mailTemplateContent.replace(NAME, receiverName).replace(DO_INVOICE_ITMES, itemsBuilder.toString());

        content.append(mailTemplateContent);

        Map<String, String> mail = new HashMap<String, String>();

        mail.put("emailSubject", emailSubject);

        mail.put("mailContent", content.toString());

        return mail;

    }

    private String getColumnDataString(String data) {

        String columnData = null;

        columnData = "<td class='dataString'><font size='2' face='Arial'><p align='center'>" + data

                + "</p></font></td>" + "n";

        return columnData;

    }

    private Element getXMLRootElement(String emailFile) {

        SAXReader reader = new SAXReader();

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(emailFile);

        Document document = null;

        try {

            document = reader.read(inputStream);

        } catch (DocumentException e) {

            LOG.error("Get XML Root Element fail, DocumentException", e);

        }

        return document.getRootElement();

    }

}

2015.05.25补记:

写这篇文章时,由于是刚写博客,所以写的各种乱,大家可以参考这篇文章:http://blog.sina.com.cn/s/blog_86e49b8f01018zet.html,其实老夫当年写这篇文章时,也是参考了这篇文章,当时没有加上参考链接,是在惭愧

2018.09.10补记:

有感于上面的代码写的实在是太烂,稍微优化了一下,供需要的小伙伴参考:


package cn.bridgeli.demo;

import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendMailUtil {

    private SendMailUtil() {
    }

    /**
     * smtp 服务器地址
     */
    private static String host = "";

    /**
     * 端口
     */
    private static String port = "465";
    /**
     * 用户名
     */
    private static String user = "";

    /**
     * 密码
     */
    private static String pwd = "";

    /**
     * 发件人邮件地址
     */
    private static String from = "";

    /**
     * 发送邮件
     *
     * @param receiveUsers 收件人邮箱地址
     * @param subject      邮件主题
     * @param text         邮件内容
     * @param affix        邮件附件地址
     * @param affixName    邮件附件名
     */
    public static void send(List<String> receiveUsers, String subject, String text, String affix, String affixName) {

        Properties props = new Properties();

        // 设置发送邮件的邮件服务器的属性
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");
        // 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
        props.put("mail.smtp.auth", "true");
        //使用ssl采用465端口发送邮件
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.socketFactory.port", port);

        //用刚刚设置好的props对象构建一个session
        Session session = Session.getDefaultInstance(props);

        // 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使用(你可以在控制台(console)上看到发送邮件的过程)
        session.setDebug(true);

        // 用session为参数定义消息对象
        MimeMessage message = new MimeMessage(session);
        Transport transport = null;
        try {
            message.setFrom(new InternetAddress(from));
            // 加载收件人地址
            int size = receiveUsers.size();
            InternetAddress[] address = new InternetAddress[size];

            for (int i = 0; i < size; i++) {
                address[i] = new InternetAddress(receiveUsers.get(i));
            }
            // to 为收件人, cc 为抄送, bcc 为密送
            message.addRecipients(Message.RecipientType.TO, address);
            message.setSubject(subject);

            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            Multipart multipart = new MimeMultipart();

            // 设置邮件的文本内容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText(text);
            multipart.addBodyPart(contentPart);

            // 添加附件
            if (StringUtils.isNotBlank(affix) && StringUtils.isNotBlank(affixName)) {

                BodyPart messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(affix);
                // 添加附件的内容
                messageBodyPart.setDataHandler(new DataHandler(source));
                // 添加附件的标题,这里很重要,通过下面的 Base64 编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                messageBodyPart.setFileName("=?GBK?B?" + enc.encode(affixName.getBytes()) + "?=");
                multipart.addBodyPart(messageBodyPart);
            }

            // 将multipart对象放到message中
            message.setContent(multipart);
            // 设置发送的日期
            message.setSentDate(new Date());
            // 保存邮件
            message.saveChanges();

            // 发送邮件
            transport = session.getTransport("smtp");
            // 连接服务器的邮箱
            transport.connect(host, user, pwd);
            // 把邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            if (null != transport) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

需要引入的依赖:


        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

全文完,如果本文对您有所帮助,请花 1 秒钟帮忙点击一下广告,谢谢。

作 者: BridgeLi,https://www.bridgeli.cn
原文链接:http://www.bridgeli.cn/archives/22
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
分类: Java 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

请输入正确的验证码