使用springboot通过阿里云企业邮箱发送邮件到指定邮箱上

1、申请阿里云企业邮箱(省略)

2、配置开启SMTP,通过SMTP程序发送邮件

参考阿里云文档:阿里邮箱如何通过SMTP程序发信_阿里邮箱(Alibaba Mail)-阿里云帮助中心

3、使用SpringBoot,发送邮件

3.1添加maven依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3.2配置 application.yml

spring:
  mail:
    host: smtp.mxhichina.com
    port: 465
    username: your-email@aliyun.com
    password: your-password
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory

3.3 编写 Java 代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

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

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("your-email@aliyun.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // true 表示支持 HTML

            mailSender.send(message);
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("邮件发送失败:" + e.getMessage());
        }
    }

    //发送携带附件的代码
    public void sendMailWithAttachment(String to, String subject, String content, String filePath) {
    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("your-email@aliyun.com");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        // 添加附件
        FileSystemResource file = new FileSystemResource(new File(filePath));
        helper.addAttachment("附件名称", file);

        mailSender.send(message);
        System.out.println("邮件发送成功!");
    } catch (MessagingException e) {
        e.printStackTrace();
        System.out.println("邮件发送失败:" + e.getMessage());
    }
   }
}

注意:阿里云服务器需要开启465端口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值