文档章节

使用Spring简化JavaMail开发

liuzhengyang
 liuzhengyang
发布于 2014/10/05 00:18
字数 956
阅读 63
收藏 0

邮件是Web应用的一个重要部分,常用于邮箱确认、找回密码、发送广告、通知等等。

Java中的JavaMail API不是很易于学习使用,容易编写出冗余易错的代码。Spring 提供了对JavaMail的有效支持,使得发送邮件变得简单愉快。

org.springframework.mail包是Spring Mail支持的顶级包,包下的MailSender,MailMessage两个核心接口和一个SimpleMessageMessage类。

其中MailSender邮件发送器,定义了发送简单邮件的方法,void send(SimpleMailMessage simpleMessage);亦可以发送多个邮件 void send(SimpleMailMessage[] simpleMessages);

MailSender的子接口JavaMailSender及其实现类JavaMailSenderImpl提供的对MIME message的支持,这样我们就可以再邮件中编写Html代码加入图片了。

MailMessage负责邮件本身的信息,包括设置主题,内容,发件人,收件人等方法。

MailMessage有两个实现类,SimpleMailMessage和MimeMailMessage,SimpleMailMessage定义了简单文本邮件,MimeMailMessage则提供了更多丰富的邮件内容支持。

I have trouble in installing PinYin input method, so i have to continue my blog using my poor english... :)And for practice 

Talk is cheap, so show the code.

First we need some basic infrastructure, like jdk,maven,and text editor or ide(recommended).

Then we create an maven project from quick-start stereotype and put some dependencies to the pom.xml.

What we need : spring-core,spring-context,spring-context-support, javax.mail and spring-test and some logging artifacts.

Here we begin our project.

Send Simple Message Email

create a spring configuration and define some beans to use

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="port" value="${mail.port}"/>
        <property name="username" value="${mail.username}"/>
        <property name="password" value="${mail.password}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
            </props>
        </property>
    </bean>

    <bean id="simpleMessage" class="org.springframework.mail.SimpleMailMessage">
        <property name="from" value="${mail.username}"/>
    </bean>

Here we create an mailSender instance implemeted by JavaMailSenderImpl and SimpleMailMessage instance.

you could replace the placeholders with your own mail setting.

Then we could use mailSender send simpleMessage for simple text email.

Put the business in a service layer class EmailService, it has a method for sending.

@Service
public class EmailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private SimpleMailMessage simpleMailMessage;

    public void sendTo(String to, String subject, String text){
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
    }
}

Then we could test this. Create a test class.

@ContextConfiguration(locations = {"/applicationContext.xml"})
public class EmailServiceTest extends AbstractTestNGSpringContextTests{
    @Autowired
    private EmailService emailService;

    @Test
    public void sendSimpleMessageTest(){
        String email = "toAddress@gmail.com";
        String subject = "This is send by liuzhengyang for fun";
        String text= "This is send by liuzhengyang  for fun" +
                "and i write &!@@@";
        emailService.sendTo(email, subject, text);
    }
}

notice your subject and email content should not be Spam like . or this email may be interceptored.Maybe i have to set up my

own mail server to break limitation for sending rate and email content.

Run this test , then i could receive this simple text email.

Send Mime Message

At production , we need some more complex email then we could use MimeMailMessage.

To use MimeMailMessage we could use MimeMessagePreparator and MimeMessageHelper for simplicity.

public void sendForRegister(final String to, final String subject){
        javaMailSender.send(new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                mimeMessageHelper.setFrom(javaMailSender.getUsername());
                mimeMessageHelper.setTo(to);
                mimeMessageHelper.setSubject(subject);
                mimeMessageHelper.setText("<html><h1>MimeMailMessage</h1></html>", true);
            }
        });
    }

For using MimeMessageHelper#setFrom , i change the declaration of JavaMailSender javaMailSender to JavaMailSenderImpl javaMailSender;

Test this , and i receive a h1 email.

And we could add attachments or inline resources to the email.And maybe the setText() in the example above make think of using Servlet to send response,

this is error prone and some hardCoding.For better choice, we could use template like Velocity.

add bean defination for velocity

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">
            <value>
                resource.loader=class
                class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </value>
        </property>
    </bean>

We create a velocity template

## for email confirm after registeration
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <style>
        body{
            text-align: center;
            font-size: large;
        }
        #title{
            color: #DD3322;
        }
    </style>
</head>
<body>
<h3>亲爱的 <span id="title">${username}</span>, 欢迎!!</h3>
<div>
    The life is beautiful and enjoy yourself!<br/>
</div>
<div>
    请点击一下链接完成确认:<br/>
    <a href="${url}">${url}</a><br/>
    (如果链接不能点击,请复制并粘贴到浏览器的地址栏,然后按回车键,该链接48小时内有效。)<br/>
</div>
<div>
    <img src="cid:img0"/>
</div>
</body>
</html>

And then use it for mailing.

public void sendForRegister(final String to, final String subject){
        javaMailSender.send(new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
                mimeMessageHelper.setFrom(javaMailSender.getUsername());
                mimeMessageHelper.setTo(to);
                mimeMessageHelper.setSubject(subject);
                Map<String, Object> model = new HashMap<String, Object>();
                model.put("username","somenewuserfromuserobject");
                model.put("url","urlfromuserobject");
                mimeMessageHelper.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,"/template/mail/registeration-confirmation.vm","UTF-8",model), true);
                ClassPathResource resource = new ClassPathResource("/image/mail/img1.png");
                System.out.println(resource.contentLength());
                mimeMessageHelper.addInline("img0", resource);
            }
        });
    }

This is the basic using of Spring Mail Support that i conclued.

There are several things to improve ,such as adding aop to email business , making this as as asynchronous task.

© 著作权归作者所有

liuzhengyang

liuzhengyang

粉丝 54
博文 18
码字总数 16157
作品 3
海淀
程序员
私信 提问
SpringBoot | 第二十六章:邮件发送

前言 讲解了日志相关的知识点后。今天来点相对简单的,一般上,我们在开发一些注册功能、发送验证码或者订单服务时,都会通过短信或者邮件的方式通知消费者,注册或者订单的相关信息。而且基...

oKong
2018/08/29
274
0
Spring Cloud 2.x系列之springboot发送邮件

虽然现在短信验证已经最流行也是最常用的验证方式;但是邮件验证还是必不可少,依然是网站的必备功能之一。什么注册验证,忘记密码或者是给用户发送营销信息都是可以使用邮件发送功能的。最早...

技术小能手
2018/10/22
0
0
【ME - Mail】之Java Mail

Java Mail 参考示例 biezhi/oh-my-email(https://github.com/biezhi/oh-my-email) journaldev.com(https://www.journaldev.com/2532/javamail-example-send-mail-in-java-smtp) 从这开始吧 ......

近在咫尺远在天涯
05/14
19
0
Java 发送邮件实现(JavaMail 和 Spring 实现)

Java 实现邮件的发送,使用 JavaMail 和 Spring 实现 一、使用 JavaMail JavaMail 是 Java 处理电子邮件相关的编程接口,但是没有被加在标准的Java开发工具包中(Java Development Kit),所...

非摩尔根
01/17
155
0
刚刚学习到的Android使用Javamail通过XOauth调用Gmail API发送邮件的方法

前景知识:OAuth,Javamail-android,Javamail api in android using XOauth 我的一个App项目需要在Service中自动发送邮件的功能,因为是后台自动发送邮件,不能出现邮件UI所以需要使用Javam...

since1986
2014/04/12
789
0

没有更多内容

加载失败,请刷新页面

加载更多

一个activity中多个handler和消息的处理过程

Ø 能否有多个handler handler的构造方法 public Handler() { …. mLooper = Looper.myLooper(); mQueue = mLooper.mQueue; mCallback = null; … } 因为几乎主要的成员变量都是从Looper中拿......

shzwork
32分钟前
3
0
一起来学Java8(一)——函数式编程

在这篇文章中,我们将了解到在Java8下如何进行函数式编程。 函数式编程 所谓的函数式编程就是把函数名字当做值进行传递,然后接收方拿到这个函数名进行调用。 首先来看下JavaScript如何进行函...

猿敲月下码
51分钟前
3
0
vue 源码 断点调试

本文转载于:专业的前端网站➥vue 源码 断点调试 1、添加sourceMap sourceMap: true 2、npm run dev 会生成vue.js.map 3、断点调试 <!DOCTYPE html><html> <head> <meta cha......

前端老手
今天
4
0
流量运营系统demo1

TopkURLMapper public class TopkURLMapper extends Mapper<LongWritable, Text, Text, FlowBean> {private FlowBean bean = new FlowBean();private Text k = new Text();@Ove......

Garphy
今天
4
0
OSChina 周六乱弹 —— 如果是个帅小伙你愿意和他出去吗

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 小小编辑推荐:《Ghost 》游戏《死亡搁浅》原声 《Ghost 》游戏(《死亡搁浅》原声) - Au/Ra / Alan Walker 手机党少年们想听歌,请使劲儿戳...

小小编辑
今天
435
15

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部