欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Mail发送邮件

程序员文章站 2022-05-25 12:58:05
...

1.添加依赖

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

2.添加spring-mail.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd ">

  

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="邮件服务器地址" />
        <property name="port" value="端口号" />
        <property name="username" value="发送者邮箱" />
        <property name="password" value="密码" />
        <property name="protocol" value="邮箱协议"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <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.smtp.timeout">25000</prop>
            </props>
        </property>

    </bean>

</beans>

3. 添加邮件工具类

package com.hnu.scw.util;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.annotation.Resource;

/**
 * JavaMail邮件工具类
 */
public class MailUtil {


    @Resource(name="mailSender")
    private JavaMailSenderImpl mailSender;

    /**
     * 发送JavaMail邮件
     * @param sendTo 收件人邮箱
     * @param sendFrom 发件人邮箱
     * @param mailSubject 邮件主题
     * @param mailContent 邮件正文
     * @throws Exception
     */
    public void SendMail(String sendTo ,String sendFrom , String mailSubject ,String mailContent) throws Exception {

        //创建邮件信息对象
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        //收件人邮箱
        mailMessage.setTo(sendTo);

        //发件人邮箱
        mailMessage.setFrom(sendFrom);

        //邮件主题
        mailMessage.setSubject(mailSubject);

        //邮件正文
        mailMessage.setText(mailContent);

        //执行发送
        mailSender.send(mailMessage);

    }






}