Spring发送邮件总结(附源码)

来源:互联网 发布:保时捷车载香水知乎 编辑:程序博客网 时间:2024/05/02 04:45

做项目用到自动发邮件功能,网上查阅很多没有给出特别详细的说明,需要自己去探索,做了很多弯路。

在此给大家分享一下自己的代码:

360网盘下载地址:http://yunpan.cn/cJzDQ3gVUHBxY  访问密码 8221



使用时 请将Spring 配置文件里的  用户名、密码、邮箱服务器 还有端口 进行修改如果不是 yeah邮箱。


如果使用maven项目:

Pom.xml

 

添加的内容

<!-- Spring3 --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>3.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>3.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>3.2.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>3.2.4.RELEASE</version></dependency><!-- Spring Email --><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-context-support</artifactId>    <version>3.2.4.RELEASE</version></dependency><!-- Javamail API -->    <dependency>      <groupId>javax.mail</groupId>      <artifactId>mail</artifactId>      <version>1.4.4</version></dependency>


如果直接导入JAR方式 ,需要引入如下JAR包


EmailUtil

package com.bookmarksClouds.util;import java.io.File;import javax.annotation.Resource;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Component;@Component("simpleMail")public class EmailUtil {  private JavaMailSender javaMailSender;  private SimpleMailMessage simpleMailMessage;      /**     *      * @方法名: sendMail      * @参数名:@param subject 邮件主题     * @参数名:@param content 邮件主题内容     * @参数名:@param to        收件人Email地址     * @param isHtml  是否是html格式(发送html时使用utf-8编码)     * @描述语:  发送邮件     * @throws MessagingException 发送发生了异常     */    public void sendMail(String subject, String content,boolean isHtml, String to) throws MessagingException    {                            MimeMessage mimeMessage = javaMailSender.createMimeMessage();                      MimeMessageHelper messageHelper =null;            if(isHtml)            {             messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");            }            else            {               messageHelper = new MimeMessageHelper(mimeMessage,true);            }            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email            messageHelper.setSubject(subject); //设置邮件主题            if(isHtml)            {             messageHelper.setText(content,true);   //设置邮件主题内容(html格式)            }            else            {             messageHelper.setText(content);   //设置邮件主题内容            }                                   messageHelper.setTo(to);          //设定收件人Email                                  javaMailSender.send(mimeMessage);      }                     /**    * 发送邮件 (包含附件)    * @param subject 主题    * @param content 内容    * @param fileAttachment 附件文件    * @param isHtml 内容是否是html格式    * @param to 发送的邮箱地址    * @throws MessagingException 发送邮件异常(失败)    */    public void sendMail(String subject, String content,boolean isHtml, File fileAttachment,String to) throws MessagingException    {                            MimeMessage mimeMessage = javaMailSender.createMimeMessage();                      MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");                        messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email            messageHelper.setSubject(subject); //设置邮件主题            if(isHtml)            {             messageHelper.setText(content,true);   //设置邮件主题内容(html格式)            }            else            {             messageHelper.setText(content);   //设置邮件主题内容            }            messageHelper.setTo(to);          //设定收件人Email            FileSystemResource file = new FileSystemResource(fileAttachment);                       messageHelper.addAttachment(file.getFilename(), file); //添加附件            javaMailSender.send(mimeMessage);          }               /**    * 发送邮件 (包含附件)    * @param subject 主题    * @param content 内容    * @param classPathResource 附件文件(附加在项目内部时候)    * @param isHtml 内容是否是html格式    * @param to 发送的邮箱地址     * @throws MessagingException     */    public void sendMail(String subject, String content,boolean isHtml, ClassPathResource classPathResource,String to)    throws MessagingException     {                            MimeMessage mimeMessage = javaMailSender.createMimeMessage();          /**             * new MimeMessageHelper(mimeMessage,true)之true个人见解:             * 关于true参数,官方文档是这样解释的:             * use the true flag to indicate you need a multipart message             * 翻译过来就是:使用true,以表明你需要多个消息             * 再去翻一下MimeMessageHelper的API,找到这样一句话:             * supporting alternative texts, inline elements and attachments             * 也就是说,如果要支持内联元素和附件就必须给定第二个参数为true             * 否则抛出 java.lang.IllegalStateException 异常             */            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");            messageHelper.setFrom(simpleMailMessage.getFrom()); //设置发件人Email            messageHelper.setSubject(subject); //设置邮件主题            if(isHtml)            {             messageHelper.setText(content,true);   //设置邮件主题内容(html格式)            }            else            {             messageHelper.setText(content);   //设置邮件主题内容            }            messageHelper.setTo(to);          //设定收件人Email            /**  FileSystemResource file = new FileSystemResource(fileAttachment);                       * ClassPathResource:很明显就是类路径资源,我这里的附件是在项目里的,所以需要用ClassPathResource             * 如果是系统文件资源就不能用ClassPathResource,而要用FileSystemResource,例:             *                        ClassPathResource file = new ClassPathResource("attachment/Readme.txt");              */          /**             * MimeMessageHelper的addAttachment方法:             * addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)             * InputStreamSource是一个接口,ClassPathResource和FileSystemResource都实现了这个接口                                      //发送附件邮件            */            ClassPathResource file = classPathResource;             messageHelper.addAttachment(file.getFilename(), file); //添加附件            javaMailSender.send(mimeMessage);              }              //Spring 依赖注入    @Resource    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {        this.simpleMailMessage = simpleMailMessage;    }      //Spring 依赖注入    @Resource    public void setJavaMailSender(JavaMailSender javaMailSender) {        this.javaMailSender = javaMailSender;    }}

Demo

package com.bookmarksClouds.test;import javax.mail.MessagingException;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.bookmarksClouds.util.EmailUtil;public class EmailUtilTest{ private  ApplicationContext factory = new ClassPathXmlApplicationContext(            new String[] {"spring/spring-smtp-mail-attachment.xml"});@Testpublic void test() {EmailUtil mail = (EmailUtil)factory.getBean("simpleMail");String html= "<html><head><META http-equiv=Content-Type content='text/html; charset=UTF-8'><title>云书签注册激活</title></head><body>欢迎使用,云书签。<br/><a href='www.baidu.com' >云书签</a><br>点击上面超链接 激活账户信息!</body><html>";        try {mail.sendMail("云书签注册自动发邮件", html,true, "***@qq.com");} catch (MessagingException e) {System.out.println("发送邮件失败!");//e.printStackTrace();}}}

 Spring配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.2.xsd           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">                      <context:annotation-config/><context:component-scan base-package="com.bookmarksClouds"/>  <bean  id ="mailSender"  class ="org.springframework.mail.javamail.JavaMailSenderImpl" >          <!--  服务器  -->           <property  name ="host"  value ="smtp.163.com"   />           <!--  端口号  -->           <property  name ="port"  value ="25"   />           <!--  用户名  -->           <property  name ="username"  value ="邮箱地址"   />           <!--   密码    -->           <property  name ="password"  value ="邮箱密码"   />           <!--  SMTP服务器验证  -->           <property  name ="javaMailProperties" >               <props >                   <!--  验证身份  -->                  <prop  key ="mail.smtp.auth" > true </prop >              </props >           </property >  </bean >  <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">        <!-- 发件人email -->        <property name="from" value="发送邮箱地址" />        <!--          收件人email        <property name="to" value="to@yeah.net" />        email主题(标题)        <property name="subject" value="Subject" />        email主题内容        <property name="text">          <value>ContentText</value>        </property>        -->    </bean>   </beans>




0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 老师打学生被家长起诉怎么办 家长在学校打了老师怎么办 老师打小孩我们家长怎么办呢? 孩子长手、腿毛怎么办 腿毛又黑又多怎么办 孩子怕老师说他怎么办 被老师骂到厌学怎么办 孩子对写作业一点也不主动怎么办 高三孩子太贪玩怎么办 玩心重的孩子该怎么办 儿子读大学不愿意读书怎么办 孩子打架全班都讨厌怎么办 孩子不爱学习怎么办 二年级 二年级孩子不爱学习总爱玩怎么办 初三孩子学习不积极怎么办 孩子学习不积极应该怎么办 小孩子贪玩不写作业怎么办 老公懒不帮忙分担家务怎么办 宝宝不喜欢早教课程单一怎么办 孩子上课不听话顶撞老师怎么办 孩子不喜欢吃水果蔬菜怎么办 中学生顶撞家长顶撞老师怎么办 .cn孩子初中上课不专心怎么办 娃儿小学二年级做不来怎么办 孩子不愿意看书沉迷电子产品怎么办 孩子自律和自控性差怎么办 婴儿7个月不喜欢吃东西怎么办 半岁宝宝太活泼怎么办 6个月宝宝太活泼怎么办 做nt宝宝太活跃怎么办 静不下心来学习怎么办 初中的孩子不爱学习怎么办 小孩不爱读书不做作业怎么办 母亲性格内向儿子也是内向怎么办 我儿子不爱吃怎么办啊 孩子练字就是记不住怎么办 孩子不愿意和小朋友玩怎么办 丈夫去世了婆婆不喜欢儿媳妇怎么办 高考看不下去书怎么办 在东莞读书读不成高中怎么办 嗓子哑了怎么办土方法