使用springboot发送qq企业邮箱邮件与附件

//pom.xml
	<properties>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>

    <repositories>
        <repository>
            <id>maven-ali</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-plugin</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <dependencies>
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.time.LocalDate;
import java.util.Date;
import java.util.Properties;


@Service
@Slf4j
public class MailService {

    public String from = "wode@qq.com";
    public String password = "TXzUeNDAUhYGjxSw";// 登录密码
    public String protocol = "smtp";// 协议
    public String port = "465";// 端口
    public String host = "smtp.exmail.qq.com";// 服务器地址

    private String theme = "通知";

    //初始化参数
    public Session initProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        // 使用smtp身份验证
        properties.put("mail.smtp.auth", "true");
        // 开启安全协议,使用SSL,企业邮箱必需
        MailSSLSocketFactory mailSSLSocketFactory = null;
        try {
            mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        properties.put("mail.smtp.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.put("mail.smtp.socketFactory.port", port);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
//        session.setDebug(true);
        return session;
    }

    public void email(String emailTo, String title, String content, String[] fileNames) {
        try {
            Session session = initProperties();
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from, from));// 发件人,可以设置发件人的别名
            // 收件人,多人接收,emailTo 逗号分隔
            InternetAddress[] internetAddressTo = InternetAddress.parse(emailTo);
            mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
            // 主题
            if (StringUtils.isEmpty(title)){
                mimeMessage.setSubject(theme);
            }else{
                mimeMessage.setSubject(title);
            }
            // 时间
            mimeMessage.setSentDate(new Date());
            // 容器类 附件
            MimeMultipart mimeMultipart = new MimeMultipart();
            // 可以包装文本,图片,附件
            if (!StringUtils.isEmpty(content)){
                MimeBodyPart bodyPart = new MimeBodyPart();
                // 设置内容 getEmailHtml是邮箱内容模板
                bodyPart.setContent(content, "text/html; charset=UTF-8");
                mimeMultipart.addBodyPart(bodyPart);
            }
            if (!StringUtils.isEmpty(fileNames) && fileNames.length > 0){
                for (String fileName:fileNames) {
                    File attachFile = new File(fileName);
                    if (attachFile.exists()){
                        MimeBodyPart attachPart = new MimeBodyPart();
                        FileDataSource fileDataSource = new FileDataSource(attachFile);
                        attachPart.setDataHandler(new DataHandler(fileDataSource));
                        attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
                        mimeMultipart.addBodyPart(attachPart);
                    }else{
                        log.error("邮件附件文件 {} 不存在",fileName);
                        return;
                    }
                }
            }
            mimeMessage.setContent(mimeMultipart);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发送邮件失败:" + emailTo + " ----" + e.getMessage());
        }
    }
}

测试用例

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class MailServiceTest {

    @Autowired
    private MailService mailService;

    @Test
    void email() {
        mailService.email("1@163.com,2@qq.com","邮件标题", "邮件内容", new String[]{"file.csv","file.csv"});
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Spring Boot发送邮件的步骤: 1. 导入Spring Boot提供的依赖[^1]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 2. 在配置文件中设置邮箱信息: ```properties spring.mail.host=smtp.qq.com spring.mail.port=587 spring.mail.username=your-email@qq.com spring.mail.password=your-email-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 3. 创建一个邮件服务类,用于发送邮件[^2]: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender mailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); mailSender.send(message); } } ``` 4. 在需要发送邮件的地方调用邮件服务类的方法发送邮件: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailService emailService; @GetMapping("/sendEmail") public String sendEmail() { String to = "recipient@example.com"; String subject = "Test Email"; String text = "This is a test email."; emailService.sendEmail(to, subject, text); return "Email sent successfully."; } } ``` 以上是使用Spring Boot发送邮件的简单示例。你可以根据自己的需求进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值