springboot发送邮件

1.控制层

@PostMapping("/sendEmail2")
@ApiOperation(value = "发送邮件")
public String sendEmail2(@RequestBody JSONObject json) {


    Email email = JSON.toJavaObject(json, Email.class);

    try {
        boolean result = emailService.sendEmail(email);//响应结果
    }
    catch (Exception e){
        e.printStackTrace();
    }

    return "Email sent successfully!";
}

2.业务层

@Override
public Boolean sendEmail(Email email) {

    boolean result=false;
    try {
        List<String> oldAttachments=email.getAttachments();
        Map<String, File> map=new HashMap<>();
        List<String> attachments=new ArrayList<>();
        // 转换附件路径
        for(String  path:oldAttachments){
            String templeFilePath=download(path,map);
            attachments.add(templeFilePath);
        }

        //发送方法
        ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                .hostname(hostname)
                .username(username)
                .password(password)
                .recipientTo(email.getRecipientTo())
                .recipientCc(email.getRecipientCc())
                .recipientBcc(email.getRecipientBcc())
                .subject(email.getSubject())
                .message(email.getMessage())
                .attachments(attachments)
                .build();
        result = client.sendExchange();//响应结果
    }catch (Exception e){
        log.error("发送邮件失败:"+e.getMessage());
    }
    return result;
}

3.工具类

package com.asset.util;/**
 * Created by admin on 2020/10/13.
 */

import com.asset.common.utils.EmptyUtil;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import net.bytebuddy.description.type.TypeList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 企业邮箱
 * @Author wyj
 * @Date 2020/10/13 17:55
 */
public class ExchangeClient {
    private static final Logger logger = LoggerFactory.getLogger(ExchangeClient.class);

    private final String hostname;
    private final ExchangeVersion exchangeVersion;
    private final String domain;
    private final String username;
    private final String password;
    private final String subject;
    private final List<String> recipientTo;
    private final List<String> recipientCc;
    private final List<String> recipientBcc;
    private final List<String> attachments;
    private final String message;

    private ExchangeClient(ExchangeClientBuilder builder) {
        this.hostname = builder.hostname;
        this.exchangeVersion = builder.exchangeVersion;
        this.domain = builder.domain;
        this.username = builder.username;
        this.password = builder.password;
        this.subject = builder.subject;
        this.recipientTo = builder.recipientTo;
        this.recipientCc = builder.recipientCc;
        this.recipientBcc = builder.recipientBcc;
        this.attachments = builder.attachments;
        this.message = builder.message;
    }

    public static class ExchangeClientBuilder {

        private String hostname;
        private ExchangeVersion exchangeVersion = ExchangeVersion.Exchange2010;
        private String domain;
        private String username;
        private String password;
        private String subject;
        private List<String> recipientTo;
        private List<String> recipientCc;
        private List<String> recipientBcc;
        private List<String> attachments;
        private String message;

        public ExchangeClientBuilder() {
            this.exchangeVersion = ExchangeVersion.Exchange2010_SP1;
            this.hostname = "";
            this.username = "";
            this.password = "";
            this.subject = "";
            this.recipientTo = new ArrayList<>(0);
            this.recipientCc = new ArrayList<>(0);
            this.recipientBcc = new ArrayList<>(0);
            this.attachments = new ArrayList<>(0);
            this.message = "";
        }

        /**
         * The hostname of the Exchange Web Service. It will be used for
         * connecting with URI https://hostname/ews/exchange.asmx
         *
         * @param hostname the hostname of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder hostname(String hostname) {
            this.hostname = hostname;
            return this;
        }

        /**
         * The Exchange Web Server version.
         *
         * @param exchangeVersion the Exchange Web Server version.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder exchangeVersion(ExchangeVersion exchangeVersion) {
            this.exchangeVersion = exchangeVersion;
            return this;
        }

        /**
         * The domain of the MS Exchange Smtp Server.
         *
         * @param domain the domain of the Active Directory. The first part of
         *               the username. For example: MYDOMAIN\\username, set the MYDOMAIN.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder domain(String domain) {
            this.domain = domain;
            return this;
        }

        /**
         * The username of the MS Exchange Smtp Server. The second part of the
         * username. For example: MYDOMAIN\\username, set the username.
         *
         * @param username the username of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder username(String username) {
            this.username = username;
            return this;
        }

        /**
         * The password of the MS Exchange Smtp Server.
         *
         * @param password the password of the MS Exchange Smtp Server.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder password(String password) {
            this.password = password;
            return this;
        }

        /**
         * The subject for this send.
         *
         * @param subject the subject for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder subject(String subject) {
            this.subject = subject;
            return this;
        }

        /**
         * You can specify a list with email addresses that will be used as cc
         * for this email send.
         *
         * @param recipientTo the list with email addresses that will be used as
         *                    cc for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientTo(List<String> recipientTo) {
            this.recipientTo = recipientTo;
            return this;
        }

        /**
         * You can specify one or more email address that will be used as cc
         * recipients.
         *
         * @param recipientCc  the first cc email address.
         * @param recipientsCc the other cc email address for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientCc(String recipientCc, String... recipientsCc) {
            // Prepare the list.
            List<String> recipients = new ArrayList<>(1 + recipientsCc.length);
            recipients.add(recipientCc);
            recipients.addAll(Arrays.asList(recipientsCc));
            // Set the list.
            this.recipientCc = recipients;
            return this;
        }

        /**
         * You can specify a list with email addresses that will be used as cc
         * for this email send.
         *
         * @param recipientCc the list with email addresses that will be used as
         *                    cc for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientCc(List<String> recipientCc) {
            this.recipientCc = recipientCc;
            return this;
        }

        /**
         * You can specify one or more email address that will be used as bcc
         * recipients.
         *
         * @param recipientBcc  the first bcc email address.
         * @param recipientsBcc the other bcc email address for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientBcc(String recipientBcc, String... recipientsBcc) {
            // Prepare the list.
            List<String> recipients = new ArrayList<>(1 + recipientsBcc.length);
            recipients.add(recipientBcc);
            recipients.addAll(Arrays.asList(recipientsBcc));
            // Set the list.
            this.recipientBcc = recipients;
            return this;
        }

        /**
         * You can specify a list with email addresses that will be used as bcc
         * for this email send.
         *
         * @param recipientBcc the list with email addresses that will be used
         *                     as bcc for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientBcc(List<String> recipientBcc) {
            this.recipientBcc = recipientBcc;
            return this;
        }

        /**
         * You can specify one or more email address that will be used as cc
         * recipients.
         *
         * @param attachment  the first attachment.
         * @param attachments the other attachments for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder attachments(String attachment, String... attachments) {
            // Prepare the list.
            List<String> attachmentsToUse = new ArrayList<>(1 + attachments.length);
            attachmentsToUse.add(attachment);
            attachmentsToUse.addAll(Arrays.asList(attachments));
            // Set the list.
            this.attachments = attachmentsToUse;
            return this;
        }

        /**
         * You can specify a list with email attachments that will be used for
         * this email send.
         *
         * @param attachments the list with email attachments that will be used
         *                    for this email send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder attachments(List<String> attachments) {
            this.attachments = attachments;
            return this;
        }

        /**
         * The body of the email message.
         *
         * @param message the body of the email message.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder message(String message) {
            this.message = message;
            return this;
        }

        /**
         * Build a mail.
         *
         * @return an EmailApacheUtils object.
         */
        public ExchangeClient build() {
            return new ExchangeClient(this);
        }
    }

    public boolean sendExchange() {
        // The Exchange Server Version.
        ExchangeService exchangeService = new ExchangeService(exchangeVersion);

        // Credentials to sign in the MS Exchange Server.
        ExchangeCredentials exchangeCredentials = new WebCredentials(username, password, domain);
        exchangeService.setCredentials(exchangeCredentials);

        // URL of exchange web service for the mailbox.
        try {
            exchangeService.setUrl(new URI("https://" + hostname + "/ews/Exchange.asmx"));
        } catch (URISyntaxException ex) {
            logger.info("An exception occurred while creating the uri for exchange service.", ex);
            return false;
        }

        // The email.
        EmailMessage emailMessage;
        try {
            emailMessage = new EmailMessage(exchangeService);
            emailMessage.setSubject(subject);
            emailMessage.setBody(MessageBody.getMessageBodyFromText(message));
        } catch (Exception ex) {
            logger.info("An exception occurred while setting the email message.", ex);
            return false;
        }

        // TO recipient.
        for (String recipient : recipientTo) {
            try {
//                if(StringUtil.isEmpty(recipient)){
//                    continue;
//                }
                emailMessage.getToRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                logger.info("An exception occurred while sstting the TO recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // CC recipient.
        for (String recipient : recipientCc) {
            try {
                if (EmptyUtil.isEmpty(recipient)) {
                    continue;
                }
                emailMessage.getCcRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                logger.info("An exception occurred while sstting the CC recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // BCC recipient
        for (String recipient : recipientBcc) {
            try {
                if (EmptyUtil.isEmpty(recipient)) {
                    continue;
                }
                emailMessage.getBccRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                logger.info("An exception occurred while sstting the BCC recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // Attachements.
        for (String attachmentPath : attachments) {
            try {
                emailMessage.getAttachments().addFileAttachment(attachmentPath);
            } catch (ServiceLocalException ex) {
                logger.info("An exception occurred while setting the attachment.", ex);
                return false;
            }
        }

        try {
            emailMessage.send();
            logger.info("An email is send.");
        } catch (Exception ex) {
            logger.info("An exception occurred while sending an email.", ex);
            return false;
        }

        return true;
    }

}

4.依赖

<dependency>
    <groupId>com.microsoft.ews-java-api</groupId>
    <artifactId>ews-java-api</artifactId>
    <version>2.0</version>
</dependency>

5.postmain的json

{

    "recipientTo":["wangyijun0510@163.com","wangyijun0510@outlook.com"],

    "recipientCc":["wangyijun0511@outlook.com"],

    "subject":"wyj test mult man",

    "message":"wyj content2",

    "attachments":["http://10.101.8.48:50001/law/user1_NAVICAT%E6%8E%88%E6%9D%83%E7%94%A8%E6%88%B7%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C_1695781087467.pdf"]

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot发送邮件需要使用JavaMailSender接口来实现。以下是一个简单的示例代码: 首先,确保在你的项目中添加了相关依赖。在pom.xml文件中添加以下代码: ```xml <dependencies> <!-- Spring Boot Starter Mail --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> ``` 然后,在你的应用程序中创建一个类来发送邮件。例如,你可以创建一个名为EmailSender的类: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; @Component public class EmailSender { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 在上述示例中,我们使用了@Autowired注解来自动注入JavaMailSender对象,该对象是由Spring Boot自动配置提供的。 现在,你可以在你的应用程序的任何地方使用EmailSender类来发送邮件。例如,你可以在控制器中使用它: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class EmailController { @Autowired private EmailSender emailSender; @PostMapping("/sendEmail") public String sendEmail(@RequestBody EmailRequest emailRequest) { emailSender.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getText()); return "Email sent successfully!"; } } ``` 上述示例中,我们创建了一个名为EmailController的REST控制器,它接收一个包含收件人、主题和内容的EmailRequest对象,并使用EmailSender发送邮件。 请注意,你需要适当配置你的邮件服务器信息。在Spring Boot的application.properties(或application.yml)文件中添加以下配置: ```yaml spring.mail.host=your-mail-server spring.mail.port=your-mail-server-port spring.mail.username=your-username spring.mail.password=your-password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true ``` 以上是一个简单的示例,你可以根据你的实际需求进行修改和扩展。希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值