spring配gmail

  1. 配置清单

  <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  

          <property name="host">  

             <value>smtp.gmail.com</value>  

         </property> 

         <property name="javaMailProperties">  

            <props>  

            <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>  

                <prop key="mail.smtp.socketFactory.fallback">false</prop>  

                <prop key="mail.smtp.port">465</prop>  

                <prop key="mail.smtp.socketFactory.port">465</prop>   

                <prop key="mail.smtp.auth">true</prop>  

                <prop key="mail.smtp.timeout">25000</prop>  

            </props>  

         </property>  

         <property name="username">  

             <value>××××××××</value>  

         </property>  

         <property name="password">  

             <value>××××××</value>  

         </property>

 

          <!-- 上是GMAIL特殊端口465或587,下是配置为25端口(默认)

<property name="host">  

             <value>smtp.163.com</value>  

         </property>  

         <property name="javaMailProperties">  

            <props>  

                 <prop key="mail.smtp.auth">true</prop>  

                 <prop key="mail.smtp.timeout">25000</prop>  

            </props>  

         </property>  

         <property name="username">  

             <value>××××××××××</value>  

         </property>  

         <property name="password">  

             <value>×××××××</value>  

         </property>    -->

    </bean> 

 

2. 注入

 

 @Autowired

 private org.springframework.mail.javamail.JavaMailSenderImpl mailSender;

 

3.发送代码

try {

MimeMessage mailMessage = mailSender.createMimeMessage();

// 设置utf-8或GBK编码,否则邮件会有乱码

MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

// 设置收件人,寄件人

messageHelper.setTo(email);

messageHelper.setFrom(mailSender.getUsername()); messageHelper.setSubject(PropertiesUtil.getProperties("html_mail_subject"));

// true 表示启动HTML格式的邮件 messageHelper.setText(FreeMarkerUtils.getHtml(targetDir, targetName), true);

// 发送邮件

mailSender.send(mailMessage); return true;

} catch (MessagingException e) {

// TODO Auto-generated catch block e.printStackTrace();

msg.append("*提示:邮件未能正常发送,请重新申请!");

return false;

}

 

 

以上只是记录,其中使用Freemarker做HTML邮件模板处理

附录:

 

properties文件:

 

#html for email to user find back password 

html_file_patch=${tempDir}/html/

http_miv = http://localhost:8080/miv-main/login/retrievePasswordJsp/

html_mail_subject = 找回MIV密码

 

附:

 

package com.miv.core.utils;

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;

import java.io.Writer;

import java.util.HashMap;

import java.util.List;

import java.util.Locale;

import java.util.Map;

 

import freemarker.template.Configuration;

import freemarker.template.DefaultObjectWrapper;

import freemarker.template.Template;

import freemarker.template.TemplateExceptionHandler;

 

public class FreeMarkerUtils {

    public static void generateHtml(String sourceDir, String sourceName, String targetDir, String targetName, List data)

            throws Exception {

 

        // 模板路径

        Configuration cfg = new Configuration();

        // 设置Configuration编码

        cfg.setEncoding(Locale.getDefault(), "UTF-8");

        // 加载free marker模板文件

        cfg.setDirectoryForTemplateLoading(new File(sourceDir));

 

        // 设置对象包装器

        cfg.setObjectWrapper(new DefaultObjectWrapper());

 

        // 设计异常处理器

        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

 

        // 定义并设置数据

        Map<String, List> map = new HashMap<String, List>();

        map.put("persons", data);

        // 获取指定模板文件

        Template template = cfg.getTemplate(sourceName);

        // 设置模板的编码

        template.setEncoding("UTF-8");

 

        // 定义输入文件,默认生成在工程根目录 ,并且设置输出流的编码;

        Writer out = new OutputStreamWriter(new FileOutputStream(targetDir + targetName), "UTF-8");

 

        // 最后开始生成

        template.process(map, out);

 

    }

 

    public static void generateHtml(String sourceDir, String sourceName, String targetDir, String targetName,

            String data) throws Exception {

 

        // 模板路径

        Configuration cfg = new Configuration();

        // 设置Configuration编码

        cfg.setEncoding(Locale.getDefault(), "UTF-8");

        // 加载free marker模板文件

        cfg.setDirectoryForTemplateLoading(new File(sourceDir));

 

        // 设置对象包装器

        cfg.setObjectWrapper(new DefaultObjectWrapper());

 

        // 设计异常处理器

        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

 

        // 定义并设置数据

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

        map.put("prop", data);

        // 获取指定模板文件

        Template template = cfg.getTemplate(sourceName);

        // 设置模板的编码

        template.setEncoding("UTF-8");

 

        // 创建路径

        mkdir(targetDir);

        // 定义输入文件,默认生成在工程根目录 ,并且设置输出流的编码;

        Writer out = new OutputStreamWriter(new FileOutputStream(targetDir + targetName), "UTF-8");

 

        // 最后开始生成

        template.process(map, out);

 

    }

 

    public static String getHtml(String targetDir, String targetName) {

        BufferedReader bufferreader = null;

        StringBuffer sb = new StringBuffer();

        FileInputStream inputStream = null;

        InputStreamReader inputStreamReader = null;

        try {

            inputStream = new FileInputStream(targetDir + targetName);

            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");

            bufferreader = new BufferedReader(inputStreamReader);

            String line = bufferreader.readLine();

            while (line != null) {

                sb.append(line);

                line = bufferreader.readLine();

            }

            bufferreader.close();

        } catch (UnsupportedEncodingException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return sb.toString();

    }

 

    // 创建文件路径

    public static void mkdir(String  targetDir) {

        File fd = null;

        try {

            fd = new File( targetDir);

            if (!fd.exists()) {

                fd.mkdirs();

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            fd = null;

        }

    }

 

    public static String getSourceDir() {

        return FreeMarkerUtils.class.getResource("/").getPath().split("WEB-INF")[0] + "WEB-INF/freemarker";

    }

}


模板:test.ftl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>    
    <title>找回密码</title>
  </head>
  <body> 
尊敬的MIV用户:
<br/>
您好!
<br/>
请点击以下链接进行下一步操作:
<br/>
<a href='${prop}'>${prop}</a>
<br/>
如果上面的链接无法点击,您也可以复制链接,粘贴到您浏览器的地址栏内,然后按“回车”键打开预设页面,完成相应功能。
<br/>
如果有其他问题,请联系我们: 谢谢!
<br/>
此为系统消息,请勿回复
  </body>
</html>

猜你喜欢

转载自zhiyu-zzy-163-com.iteye.com/blog/1684617