当前位置: 首页 > news >正文

使用Spring整合javaMail发用邮件

1.导入javamail.jar        自行百度下载

2.使用模板发送邮件架包 freemarker.jar

3.Spring配置文件  以及架包这里就不需要说了吧,如果不明白的发我Email :xkjava@sina.com

 

 

//邮件信息设置类 main.java

package cn.jbit.email;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

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

public class Mail {
    private JavaMailSender mailSender;
    private Configuration configuration;

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }


    public JavaMailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    //模板設置
    private String getMailText() {

        String htmtext = "";
        // 发信内容
        String mailcontent = "你好,欢迎使用尊云服务器,在这里,你的数据更加安全、性能更加稳定!";
        try {
            // 获取实例模板
            Template template = configuration.getTemplate("Template02.ftl");

            // 通过map传递动态数据
            Map map = new HashMap();
            map.put("name", "简单");
            map.put("content", mailcontent);
            htmtext = FreeMarkerTemplateUtils.processTemplateIntoString(
                    template, map);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return htmtext;

    }

    //发送邮件
    public void send() throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true,"UTF-8");
        try {
            helper.setFrom("xkjava@163.com");
            helper.setTo("xkjava@sina.com");
            helper.setSubject("歡迎來到員工社區");
            helper.setText(getMailText(),true);
            
        //多个附件发送,先放进集合,注意这里的文件路径 List
<String> strFilePath = new ArrayList<String>();
                //文件路径 strFilePath.add(
"cn/jbit/template/1.doc"); strFilePath.add("cn/jbit/template/he_header.png"); for (String strfile : strFilePath) { //带附件发送邮件 ClassPathResource file = new ClassPathResource(strfile); helper.addAttachment(file.getFilename(), file.getFile()); } //发送 mailSender.send(message); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); /* simpleMailMessage.setFrom("kzhan8082@163.com"); simpleMailMessage.setTo("xkjava@sina.com"); simpleMailMessage.setText("HelloJavaMail!!!!"); simpleMailMessage.setSubject("Hello");*/ //mailSender.send(simpleMailMessage); // 发送邮件 } }

 

 

 

//Spring  applicationContext.xml 配置文件

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!--通过模板发送邮件-->
    <bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
        <!-- 模板路徑 -->    <!--模板路径,这里根据自己的模板路径来,模板的后缀名为 .ftl-->
        <property name="templateLoaderPath" value="cn/jbit/template"></property>
        
        <!-- 设置FreeMarke环境变量 -->
        <property name="freemarkerSettings">
            <props>
                  <!--这里暂时不配,防止中文乱码-->
            </props>
        </property>
    </bean>



    <!-- 设置邮件信息 这里就是用163的邮箱做demo,方便-->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.163.com"></property>
        <property name="port" value="25"></property>
        <property name="username" value="邮箱账户"></property>
        <property name="password" value="邮箱密码"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="protocol" value="smtp"></property>
        <property name="javaMailProperties">
            <props>
                <!-- 设置smtp服务器需要用户验证 -->
                <prop key="mail.smtp.auth">true</prop>
            </props>
        
        </property>
    </bean>
    
    <!-- IOC注入 -->
    <bean id="mailsend" class="cn.jbit.email.Mail">
        <property name="mailSender" ref="mailSender"></property>
        <property name="configuration" ref="freeMarkerConfiguration"></property>
    </bean>

    
</beans>

 

 

//测试类MailTest.java

package cn.jbit.email;

import javax.mail.MessagingException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MialTest {

    /**
     * @param args
     * @throws MessagingException 
     */
    public static void main(String[] args) throws MessagingException {
        // TODO Auto-generated method stub
        /*Mail mail = new Mail();
        mail.send();*/    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        Mail mail02 = (Mail)applicationContext.getBean("mailsend");
        mail02.send();
        System.out.println("success");
    }

}

 

 

 

这里的功能比较多,注意看设置邮件信息的 mail.java  类。里面涉及了多个附件的发送,是用模板发送。注意导入命名空间的架包。

 

 

 

转载于:https://www.cnblogs.com/kzhan/p/3818014.html

相关文章:

  • v​n​c​服​务​​安​装​与配置
  • 布局文件提示错误“No orientation specified, and the default is horizontal. This is a common so...”...
  • BZOJ-2743 采花
  • vs2012 发布网站丢失文件
  • hdu 1576扩展欧几里得算法
  • WCF入门教程:WCF基础知识问与答(转)
  • 《海量数据库解决方式》读后感
  • Winsock网络编程笔记(1)----入门
  • php中body下出现莫名空白字符
  • 关于ios 运行时 介绍的比较详细的帖子
  • IIS应用程序池监控
  • 理解 backbone.js 中的 bind 和 bindAll 方法,关于如何在方法中指定其中的 this,包含apply方法的说明...
  • 距离变换DT
  • 2-3. 逆序的三位数(10)
  • 发布/订阅消息传送模型
  • [PHP内核探索]PHP中的哈希表
  • 【EOS】Cleos基础
  • 【译】React性能工程(下) -- 深入研究React性能调试
  • Akka系列(七):Actor持久化之Akka persistence
  • co模块的前端实现
  • Flannel解读
  • github指令
  • hadoop集群管理系统搭建规划说明
  • jdbc就是这么简单
  • js正则,这点儿就够用了
  • Netty 框架总结「ChannelHandler 及 EventLoop」
  • STAR法则
  • 纯 javascript 半自动式下滑一定高度,导航栏固定
  • 从零搭建Koa2 Server
  • 关于springcloud Gateway中的限流
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 吐槽Javascript系列二:数组中的splice和slice方法
  • 微信小程序填坑清单
  • 小程序01:wepy框架整合iview webapp UI
  • 找一份好的前端工作,起点很重要
  • 职业生涯 一个六年开发经验的女程序员的心声。
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • #我与Java虚拟机的故事#连载17:我的Java技术水平有了一个本质的提升
  • $(function(){})与(function($){....})(jQuery)的区别
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (1)Nginx简介和安装教程
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (带教程)商业版SEO关键词按天计费系统:关键词排名优化、代理服务、手机自适应及搭建教程
  • (二)pulsar安装在独立的docker中,python测试
  • (附源码)ssm教材管理系统 毕业设计 011229
  • (力扣)1314.矩阵区域和
  • (利用IDEA+Maven)定制属于自己的jar包
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (三)uboot源码分析
  • (已解决)vue+element-ui实现个人中心,仿照原神
  • (译)2019年前端性能优化清单 — 下篇
  • (转)linux 命令大全
  • .NET 8.0 中有哪些新的变化?