邮件服务实现

本文展示了如何使用Spring框架整合JavaMail实现邮件发送功能,包括配置系统邮箱、发送HTML格式邮件等步骤,并提供了完整的代码实现及示例。

pom.xml

 <!-- 邮件发送 -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.1</version>
        </dependency>

EmailService

package net.deniro.email;

/**
 * 邮件服务
 *
 * @author deniro
 *         15-2-5下午3:11
 */
public interface EmailService {
    /**
     * 发送html格式的邮件
     *
     * @param to       接收地址
     * @param subject  邮件主题
     * @param htmlText 邮件内容
     * @throws EmailException
     */
    void sendMail(String to, String subject, String htmlText) throws EmailException;
}

EmailServiceImpl

package net.deniro.email;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

import static javax.mail.Message.RecipientType.TO;

/**
 * @author deniro
 *         15-2-5下午3:16
 */
public class EmailServiceImpl implements EmailService {

    private JavaMailSender javaMailSender;
    /**
     * 系统邮箱
     */
    private String systemEmail;

    public static void main(String[] args) {
        try {
            String host = "smtp.sina.com";
            final String from = "lisq047@sina.com";
            String to = "lisq047@163.com";

            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");

            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, "deniro");
                }
            };

            Session session = Session.getDefaultInstance(props, authenticator);

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipients(TO, String.valueOf(new InternetAddress(to)));

            message.setSubject("测试");

            message.setText("测试内容");

            message.saveChanges();

            Transport.send(message);

        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    @Override
    public void sendMail(String to, String subject, String htmlText) throws EmailException {
        try {
            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper msgHelper = new MimeMessageHelper(msg, "utf-8");//解决中文乱码

            msgHelper.setFrom(systemEmail);
            msgHelper.setTo(to);
            msgHelper.setSubject(subject);
            msgHelper.setText(htmlText, true);//html格式


            javaMailSender.send(msg);
        } catch (MessagingException e) {
            throw new EmailException("邮件发送失败。", e);
        }
    }

    public JavaMailSender getJavaMailSender() {
        return javaMailSender;
    }

    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public String getSystemEmail() {
        return systemEmail;
    }

    public void setSystemEmail(String systemEmail) {
        this.systemEmail = systemEmail;
    }
}


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

    <!--载入属性文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="location" value="classpath:service.properties"></property>
    </bean>

    <!--邮件发送-->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="protocol" value="${email.protocol}"/>
        <property name="host" value="${email.host}"/>
        <property name="port" value="${email.port}"/>
        <property name="username" value="${email.username}"/>
        <property name="password" value="${email.password}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.${email.protocol}.auth">${email.auth}</prop>
            </props>
        </property>
    </bean>

    <!--邮件服务-->
    <bean id="emailService" class="net.deniro.email.EmailServiceImpl">
        <property name="javaMailSender" ref="javaMailSender"/>
        <property name="systemEmail" value="${email.systemEmail}"/>
    </bean>


</beans>


service.properties


email.protocol=smtp
email.host=smtp.sina.com
email.port=25
email.username=lisq047
email.password=******
email.auth=true
email.systemEmail=lisq047@sina.com

邮件发送结果:




调用前,记得先开启系统邮箱的SMTP服务:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值