Spring集成Java Mail

本文介绍如何使用JavaMail发送电子邮件,包括简单的文本邮件和带有HTML格式及附件的复杂邮件。通过整合Spring框架,实现邮件发送的配置管理和代码简化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Mail简单使用

1、导入jar包

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.4</version>
</dependency>

2、使用Java Mail

public void testJavaMail() throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.163.com");    // 使用163发件服务器
    props.put("mail.smtp.auth", "true");            // 启用验证

    Session session = Session.getInstance(props);
    session.setDebug(true);

    // 构造信息体
    MimeMessage message = new MimeMessage(session);

    // 发件地址
    Address address = new InternetAddress("发件地址@163.com");
    message.setFrom(address);

    // 收件
    Address toAddress = new InternetAddress("收件邮箱");
    message.setRecipient(RecipientType.TO, toAddress);

    // 主题
    message.setSubject("主题");

    // 正文
    message.setText("正文");
    message.saveChanges();

    Transport transport = session.getTransport("smtp");

    transport.connect("smtp.163.com", "发件邮箱", "邮箱密码");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

Spring集成Java Mail

1、导入jar包

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.4</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.2.4.RELEASE</version>
</dependency>

2、编写Java Mail配置文件:mail.properties

#发件服务器主机
mail.smtp.host=smtp.163.com
mail.smtp.auth=true
mail.username=发件邮箱用户名
mail.password=密码
mail.from=发件邮箱

3、编写Java Mail的Spring配置文件:applicationContext-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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd    
    http://www.springframework.org/schema/context    
    http://www.springframework.org/schema/context/spring-context.xsd">

    <description>Java Mail Properties</description>

    <context:property-placeholder location="classpath:mail.properties"/>

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

    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.smtp.host}"></property>
        <property name="username" value="${mail.username}"></property>
        <property name="password" value="${mail.password}"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.debug">true</prop>
                <prop key="mail.smtp.timeout">0</prop>
            </props>
        </property>
    </bean>

</beans>

4、编写代码

(1)发送简单文本邮件
@Test
public void testSimpleJavaMail() {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

    SimpleMailMessage mailMessage = (SimpleMailMessage) context.getBean("mailMessage");
    JavaMailSenderImpl mailSender = (JavaMailSenderImpl) context.getBean("mailSender");

    mailMessage.setTo("收件邮箱");
    mailMessage.setSubject(主题");
    mailMessage.setText("内容");

    mailSender.send(mailMessage);
}
(2)发送带附件的邮件
@Test
public void testJavaMail() throws MessagingException {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    JavaMailSender sender = (JavaMailSender) context.getBean("mailSender");

    MimeMessage message = sender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setFrom("发件邮箱");
    helper.setTo("收件邮箱");
    helper.setSubject("主题");

    helper.setText("<html><head></head><body><h1>Title</h1>"
                +"<a href=http://www.baidu.com>baidu</a>"   + "<img src=cid:image/></body></html>", true);

    FileSystemResource image = new FileSystemResource(new File("图片路径"));
    helper.addInline("image", image);

    FileSystemResource zip = new FileSystemResource(new File("附件路径"));
    helper.addAttachment("附件名称", zip);

    sender.send(message);
}

发送邮件的工具类

MailUtils.java

public class MailUtils {

    public static void sendMessage(String toAddr, String subject, String content) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com");    // 设置发件服务器
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props);
        session.setDebug(true);

        // 构造信息体
        MimeMessage message = new MimeMessage(session);

        // 发件地址
        Address address = new InternetAddress("发件邮箱");
        message.setFrom(address);

        // 收件
        Address toAddress = new InternetAddress(toAddr);
        message.setRecipient(RecipientType.TO, toAddress);

        // 主题
        message.setSubject(subject);

        // 正文
        message.setText(content);
        message.saveChanges();

        Transport transport = session.getTransport("smtp");

        transport.connect("smtp.163.com", "发件邮箱", "密码");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值