java mail 通过 freemarker 发送邮件

java mail 通过 freemarker 发送邮件

  1. 理解 java mail 核心类:
    1). MimeMessage 对象就是一封邮件。
    2). Session 定义系统属性信息。

  2. 具体代码如下:
    1). controller 层代码如下:

package com.tarena.mail.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tarena.mail.service.SendEmail;

@RequestMapping("/email")
@Controller
public class MailController {

    private Logger logger = Logger.getLogger(MailController.class);

    @Autowired
    private SendEmail sendEmail;

    @RequestMapping("/sendEmail")
    public void sendEmail(){
        logger.debug("enter sendEamil method...");
        sendEmail.sendMail();
        logger.debug("exit sendEmail method...");
    }
}

2). service 层代码如下:

package com.tarena.mail.service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.tarena.freemarker.dto.User;
import com.tarena.mail.config.ConfigMessage;
import com.tarena.mail.controller.MailController;
import com.tarena.mail.dto.Mail_authenticator;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service
public class SendEmail {

    private Logger logger = Logger.getLogger(MailController.class);

    @Autowired
    private FreeMarkerConfigurer freemarker;

    public void sendMail() {

        // 发件人地址
        String from = "[email protected]";
        // 收件人地址
        String to = "[email protected]";

        // 设定系统属性
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", ConfigMessage.getProperty("mail.smtp.host"));
        properties.put("mail.smtp.port", ConfigMessage.getProperty("mail.smtp.port"));
        properties.put("mail.smtp.auth", ConfigMessage.getProperty("mail.smtp.auth"));

        // 获取网络连接 授权
        Mail_authenticator auth = new Mail_authenticator("[email protected]", "Yd123456");
        // 获取 mail session 对象
        Session session = Session.getInstance(properties, auth);
        // 创建 消息 对象
        MimeMessage message = new MimeMessage(session);

        try {
            // 创建 MimeMessageHelper 对象
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true, "utf-8");
            // 设置发件人地址
            mimeMessageHelper.setFrom(new InternetAddress(from));
            // 设置收件人地址
            mimeMessageHelper.setTo(new InternetAddress(to));

            // 设置主题
            mimeMessageHelper.setSubject("Hello world");

            // message.setText("This is my first sending email by java mail.");

            // 获取模版对象
            Template template = freemarker.getConfiguration().getTemplate("user.ftl");

            // 准备的 model data
            Map map = new HashMap();
            map.put("user", new User("Hellen", 20));

            // 解析 模版和 数据
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

            // file 本地路径下的文件
            File file = new File("G:/chrome download/学生.xls");
            // 添加附件
            mimeMessageHelper.addAttachment("学生.xls", file);

            // 添加内嵌图片
            mimeMessageHelper.addInline("picture", new File("E:/图片/美图图库/baby.jpg"));

            // 设置 消息内容
            mimeMessageHelper.setText(content, true);

            // 发送消息
            Transport.send(message);
            System.out.println("send email successfully...");

        } catch (AddressException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (TemplateException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

}
  1. mail_authenticator dto 代码如下:
package com.tarena.mail.dto;

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

public class Mail_authenticator extends Authenticator{

    private String userName;
    private String password;

    public Mail_authenticator(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }

    public Mail_authenticator() {
        super();
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password) ;
    }

}
  1. spring 配置文件如下:

<bean
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="ui/template" />
    <property name="defaultEncoding" value="UTF-8" />
bean>

<bean
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    <property name="suffix" value=".ftl" />
    <property name="contentType" value="text/html;charset=UTF-8" />
    
    <property name="requestContextAttribute" value="rc" />
    <property name="order" value = "1" />
bean>

5). user.ftl 模版文件如下:

<html>
<head>
head>
<body>
    <table border="2 red solid">
        <tr>
            <td>usernametd>
            <td>agetd>
        tr>
        <tr>
            <td>${user.userName}td>
            <td>${user.age}td>
        tr>
    table>
    <div>
        <img src="cid:picture"/>
    div>
body>
html>

你可能感兴趣的:(java,mail,+,freemarker)