Java和Spring:发送邮件(以QQ邮箱为例)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fly910905/article/details/88894406

Maven配置

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
    </dependencies>
    

邮箱授权码获取(QQ邮箱)

https://blog.csdn.net/fly910905/article/details/80331842

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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
       default-lazy-init="true">

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>

    <!-- Activates scanning of @Service -->
    <context:component-scan base-package="com.newcapec.cloudpay.service"/>

    <aop:aspectj-autoproxy/>


    <!--JavaMailSender配置-->
    <!-- Production implementation of the JavaMailSender interface, supporting
        both JavaMail MimeMessages and Spring SimpleMailMessages -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.qq.com" />
        <property name="port" value="587" />
        <!--<property name="username" value="[email protected]" />
        <property name="password" value="krbcsngqozefhhgf"/>-->
        <property name="username" value="[email protected]" />
        <property name="password" value="gngtkbtcgohgidde"/>

        <!-- The name of the property, following JavaBean naming conventions -->
        <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
    </bean>
</beans>

邮件发送接口

import java.io.FileNotFoundException;

import javax.mail.MessagingException;


/**
 * @Title: 邮件发送接口
 * @ClassName: com.cloudpay.service.mail.MailSenderService.java
 * @Description:
 *
 * @Copyright 2016-2018  - Powered By 研发中心
 * @author: FLY
 * @date:  2019-03-29 9:14
 * @version V1.0
 */
public interface MailSenderService {

    /**
     * @Title: 发普通邮件,msgBody是普通的文本
     * @methodName:  sendEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param msgBody 邮件内容
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:21
     */
    void sendEmail(String toAddress, String fromAddress, String subject, String msgBody);

    /**
     * @Title:  发html邮件或者普通邮件,msgBody是html文本或者普通文本
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:24
     */
    void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody) throws MessagingException;

    /**
     * @Title: 发html邮件或者普通邮件,msgBody是html文本或者普通文本,带附件
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @param filePath 附件路径
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:27
     */
    void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody, String filePath)
            throws MessagingException, FileNotFoundException;

    /**
     * @Title: 发html邮件或者普通邮件,msgBody是html文本或者普通文本,带附件
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @param filePath 附件路径
     * @param fileName 附件名称
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:27
     */
    void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody, String filePath,
                       String fileName) throws MessagingException, FileNotFoundException;
}

邮件发送实现

package com.newcapec.cloudpay.service.mail.impl;

import java.io.File;
import java.io.FileNotFoundException;

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

import com.newcapec.cloudpay.service.mail.MailSenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * @Title: 邮件发送实现类
 * @ClassName: com.newcapec.cloudpay.service.mail.impl.MailSenderServiceImpl.java
 * @Description:
 *
 * @Copyright 2016-2018 FLY - Powered By 研发中心
 * @author: FLY
 * @date:  2019-03-29 9:14
 * @version V1.0
 */
@Service
public class MailSenderServiceImpl implements MailSenderService {

    @Autowired
    private JavaMailSender mailSender;


    /**
     * @Title: 发普通邮件,msgBody是普通的文本
     * @methodName:  sendEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param msgBody 邮件内容
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:21
     */
    @Override
    public void sendEmail(String toAddress, String fromAddress, String subject, String msgBody) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(fromAddress);
        simpleMailMessage.setTo(toAddress);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(msgBody);
        mailSender.send(simpleMailMessage);
    }


    /**
     * @Title:  发html邮件或者普通邮件,msgBody是html文本或者普通文本
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:24
     */
    @Override
    public void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody)
            throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
        helper.setTo(toAddress);
        helper.setFrom(fromAddress);
        helper.setText(htmlBody, true);
        helper.setSubject(subject);

        mailSender.send(message);

    }


    /**
     * @Title: 发html邮件或者普通邮件,msgBody是html文本或者普通文本,带附件
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @param filePath 附件路径
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:27
     */
    @Override
    public void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody, String filePath)
            throws MessagingException, FileNotFoundException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setTo(toAddress);
        helper.setFrom(fromAddress);
        helper.setText(htmlBody, true);
        helper.setSubject(subject);
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("找不到附件:" + filePath);
        }
        helper.addAttachment(file.getName(), file);
        mailSender.send(message);
    }



    /**
     * @Title: 发html邮件或者普通邮件,msgBody是html文本或者普通文本,带附件
     * @methodName:  sendHtmlEmail
     * @param toAddress 收件人
     * @param fromAddress 发送人
     * @param subject 邮件主题
     * @param htmlBody 邮件内容
     * @param filePath 附件路径
     * @param fileName 附件名称
     * @return void
     * @Description:
     *
     * @author: FLY
     * @date:  2019-03-29 9:27
     */
    @Override
    public void sendHtmlEmail(String toAddress, String fromAddress, String subject, String htmlBody, String filePath,
                              String fileName) throws MessagingException, FileNotFoundException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setTo(toAddress);
        helper.setFrom(fromAddress);
        helper.setText(htmlBody, true);
        helper.setSubject(subject);
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("找不到附件:" + filePath);
        }
        helper.addAttachment(fileName, file);
        mailSender.send(message);
    }
}

邮件发送测试

import com.newcapec.cloudpay.service.mail.MailSenderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.FileNotFoundException;
import java.util.Properties;

/**
 * @version V1.0
 * @Title: 邮件发送测试
 * @ClassName: service.MailSendTest.java
 * @Description:
 * @Copyright 2016-2018 FLY - Powered By 研发中心
 * @author: FLY
 * @date: 2019-03-29 14:39
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext-spring.xml"})
public class MailSendTest {

    @Autowired
    private MailSenderService srv;


    @Test
    public void testTextMail() {
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "测试主题";
        String text = "测试内容";
        srv.sendEmail(to, from, subject, text);
    }

    @Test
    public void testHtmlMail() throws MessagingException {
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "测试主题";
        String text = "<html><a href=\"https://blog.csdn.net/fly910905/article/details/79131755\">Swagger2离线文档:PDF和Html5格式</a></html>";
        srv.sendHtmlEmail(to, from, subject, text);
    }

    @Test
    public void testHtmlMailWithAttach() throws MessagingException {
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "测试主题";
        String text = "<html><a href=\"https://blog.csdn.net/fly910905/article/details/79131755\">Swagger2离线文档:PDF和Html5格式</a></html>";

        String filePath = "d://测试附件.txt";
        try {
            srv.sendHtmlEmail(to, from, subject, text, filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testHtmlMailWithAttachAndName() throws MessagingException {
        String from = "[email protected]";
        String to = "[email protected]";
        String subject = "测试主题";
        String text = "<html><a href=\"https://blog.csdn.net/fly910905/article/details/79131755\">Swagger2离线文档:PDF和Html5格式</a></html>";
        String filePath = "d://测试附件.txt";
        String fileName = "测试附件123.txt";
        try {
            srv.sendHtmlEmail(to, from, subject, text, filePath, fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void sendText() {

        // 邮件发送
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        // 参考QQ邮箱帮助中心
        mailSender.setHost("smtp.qq.com"); // QQ邮箱smtp发送服务器地址
        //mailSender.setPort(465); // QQ这个端口不可用
        mailSender.setPort(587);// 端口号
        mailSender.setUsername("[email protected]"); // 使用你自己的账号
        mailSender.setPassword("gngtkbtcgohgidde"); // 授权码-发短信获取
        Properties properties = new Properties();
        //properties.setProperty("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.debug", "true");
        mailSender.setJavaMailProperties(properties);
        // 邮件信息
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("[email protected]"); // 发件人邮箱
        msg.setTo("[email protected]"); // 收件人邮箱
        msg.setSubject("测试Spring邮件"); // 标题
        msg.setText("您的订单号码: 20181120075; 请勿告诉别人!"); // 文本信息
        try {
            mailSender.send(msg);
            System.out.println("邮件发送成功!"); // 没有报错就是好消息 :-)
        } catch (MailException ex) {
            System.err.println("发送失败:" + ex.getMessage());
        }

    }


    @Test
    public void sendHtml() throws MessagingException {

        // 邮件发送
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        // 参考QQ邮箱帮助中心
        mailSender.setHost("smtp.qq.com"); // QQ邮箱smtp发送服务器地址
        //mailSender.setPort(465); // QQ这个端口不可用
        mailSender.setPort(587);// 端口号
        mailSender.setUsername("[email protected]"); // 使用你自己的账号
        mailSender.setPassword("gngtkbtcgohgidde"); // 授权码-发短信获取
        Properties properties = new Properties();
        //properties.setProperty("mail.smtp.host", "smtp.qq.com");
        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.debug", "true");
        mailSender.setJavaMailProperties(properties);
        // 邮件信息
        MimeMessage message = mailSender.createMimeMessage();
        // 防止被QQ邮箱处理为垃圾邮件
        message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
        MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
        helper.setFrom("[email protected]"); // 发件人邮箱
        helper.setTo("[email protected]"); // 收件人邮箱
        String text = "<html><h3>尊敬的用户,您好!</h3><a href=\"https://blog.csdn.net/fly910905/article/details/79131755\">Swagger2离线文档:PDF和Html5格式</a></html>";
        helper.setSubject("Swagger2离线文档"); // 标题

        helper.setText(text, true);
        try {
            mailSender.send(message);
            System.out.println("邮件发送成功!");
        } catch (MailException ex) {
            System.err.println("发送失败:" + ex.getMessage());
        }

    }
}

猜你喜欢

转载自blog.csdn.net/fly910905/article/details/88894406