java通过exchange发送邮件(带附件)

1.在项目中引入一下jar包

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

2.以下是工具类

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


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;

public class ExchangeClient {

    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 String recipientTo;
    private final List<String> recipientToList;
    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.recipientToList = builder.recipientToList;
        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;
        private String domain;
        private String username;
        private String password;
        private String subject;
        private String recipientTo;
        private List<String> recipientToList;
        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 = "";
            this.recipientToList= new ArrayList<>(0);
            this.recipientCc = new ArrayList<>(0);
            this.recipientBcc = new ArrayList<>(0);
            this.attachments = new ArrayList<>(0);
            this.message = "";
        }

        /**
         * @Desc Exchange Web服务的主机名
         * @param hostname
         * @return
         */
        public ExchangeClientBuilder hostname(String hostname) {
            this.hostname = hostname;
            return this;
        }

        /**
         * @Desc Exchange Web服务器版本。
         * @param exchangeVersion
         * @return
         */
        public ExchangeClientBuilder exchangeVersion(ExchangeVersion exchangeVersion) {
            this.exchangeVersion = exchangeVersion;
            return this;
        }

        /**
         * @Desc smtp服务器的域。
         * @param domain
         * @return
         */
        public ExchangeClientBuilder domain(String domain) {
            this.domain = domain;
            return this;
        }

        /**
         * @Desc MS Exchange Smtp服务器的用户名 发送用户
         * @param username
         * @return
         */
        public ExchangeClientBuilder username(String username) {
            this.username = username;
            return this;
        }

        /**
         * @Desc 发送用户的密码
         * @param password
         * @return
         */
        public ExchangeClientBuilder password(String password) {
            this.password = password;
            return this;
        }

        /**
         * @Desc 邮件主题
         * @param subject
         * @return
         */
        public ExchangeClientBuilder subject(String subject) {
            this.subject = subject;
            return this;
        }

        /**
         * @Desc 收件人
         * @param recipientTo
         * @return
         */
        public ExchangeClientBuilder recipientTo(String recipientTo) {
            this.recipientTo = recipientTo;
            return this;
        }

        /**
         * @Desc 收件人
         * @param recipientToList
         * @return
         */
        public ExchangeClientBuilder recipientToList(List<String> recipientToList) {
            this.recipientToList = recipientToList;
            return this;
        }

        /**
         * @Desc 抄送人
         * @param recipientCc
         * @param recipientsCc
         * @return
         */
        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;
        }

        /**
         * @Desc 抄送人
         * @param recipientCc
         * @return
         */
        public ExchangeClientBuilder recipientCc(List<String> recipientCc) {
            this.recipientCc = recipientCc;
            return this;
        }

        /**
         * @Desc 密送人
         * @param recipientBcc
         * @param recipientsBcc
         * @return
         */
        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;
        }

        /**
         * @Desc 密送人
         * @param recipientBcc
         * @return
         */
        public ExchangeClientBuilder recipientBcc(List<String> recipientBcc) {
            this.recipientBcc = recipientBcc;
            return this;
        }

        /**
         * @Desc 附件
         * @param attachment
         * @param attachments
         * @return
         */
        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;
        }

        /**
         * @Desc 附件
         * @param attachments
         * @return
         */
        public ExchangeClientBuilder attachments(List<String> attachments) {
            this.attachments = attachments;
            return this;
        }

        /**
         * @Desc 邮件正文
         * @param message
         * @return
         */
        public ExchangeClientBuilder message(String message) {
            this.message = message;
            return this;
        }

        /**
         * @Desc 创建邮件
         * @return
         */
        public ExchangeClient build() {
            return new ExchangeClient(this);
        }
    }

    /**
     * @Desc 发送邮件
     * @return
     */
    public Map<String, Object> sendExchange() {
        Map<String, Object> map=new HashMap<>();
        // Exchange服务器版本。
        ExchangeService exchangeService = new ExchangeService(exchangeVersion);

        // 要在MS Exchange服务器上签名的凭据。
        ExchangeCredentials exchangeCredentials = new WebCredentials(username, password, domain);
        exchangeService.setCredentials(exchangeCredentials);

        // 邮箱的exchange web服务的URL
        try {
            exchangeService.setUrl(new URI("https://" + hostname + "/ews/Exchange.asmx"));
        } catch (URISyntaxException ex) {
            logger.error("创建与服务端的连接发生异常", ex);
            if(exchangeService!=null) {
                exchangeService.close();
            }
            map.put("error","创建与服务端的连接发生异常");
            return map;
        }

        // 设置邮件信息
        EmailMessage emailMessage;
        try {
            emailMessage = new EmailMessage(exchangeService);
            emailMessage.setSubject(subject);
            emailMessage.setBody(MessageBody.getMessageBodyFromText(message));
        } catch (Exception ex) {
            logger.error("设置邮件发生异常", ex);
            map.put("error","设置邮件发生异常");
            return map;
        }

        // 设置收件人
        for (String temp : recipientToList) {
            try {
                emailMessage.getToRecipients().add(temp);
            } catch (ServiceLocalException ex) {
                logger.error("设置邮件收件人发生异常.", ex);
                map.put("error", "设置邮件收件人发生异常");
                return map;
            }
        }

//        // 设置收件人
//        try {
//            emailMessage.getToRecipients().add(recipientTo);
//        } catch (ServiceLocalException ex) {
//            logger.error("设置邮件收件人发生异常.", ex);
//            map.put("error","设置邮件收件人发生异常");
//            return map;
//        }

        // 设置抄送人
        for (String recipient : recipientCc) {
            try {
                emailMessage.getCcRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                logger.error("设置邮件抄送人发生异常.", ex);
                map.put("error","设置邮件抄送人发生异常");
                return map;
            }
        }

        // 设置邮件密送人
        for (String recipient : recipientBcc) {
            try {
                emailMessage.getBccRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                logger.error("设置邮件密送人发生异常.", ex);
                map.put("error","设置邮件密送人发生异常");
                return map;
            }
        }

        // 设置附件
        for (String attachmentPath : attachments) {
            try {
                emailMessage.getAttachments().addFileAttachment(attachmentPath);
            } catch (ServiceLocalException ex) {
                logger.error("设置邮件附件发生异常", ex);
                map.put("error","设置邮件附件发生异常");
                return map;
            }
        }

        try {
            emailMessage.send();
            logger.info("邮件发送成功.");
        } catch (Exception ex) {
            logger.error("邮件发送异常.", ex);
            map.put("error","邮件发送异常");
            return map;
        }
        map.put("success","邮件发送成功");
        return map;
    }

}

3.以下为测试代码

import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件发送工具类
 *
 */
public class MailTool {
    private static final Logger logger = LoggerFactory.getLogger(MailTool.class);
    private static String PROPERTIES_CONFIG = "mailConfig.properties";
    #邮箱exchange服务地址,如果不知道找运维
    private static String HOSTNAME = "xxxxx.com";
    #邮箱地址
    private static String USERNAME="xxxxx.com";
    #邮箱密码
    private static String PASSWORD ="xxxxx";
    private static Properties properties;
    private static String[] ERRORMSG_RECIPIENTCCS = {};
    public static String DOMAIN_NAME;

    public static void main(String[] args) {
        StringBuilder builder = new StringBuilder();
        builder.append(".......,<BR>" +
                "...........................<BR><BR>");
        List<String> attachments=new ArrayList<>();
        attachments.add("D:\\upload\\xxx.xlsx");
        List<String> fasong=new ArrayList<>();
        fasong.add("12345678@163.com");
        List<String> screct=new ArrayList<>();
        fasong.add("123456@163.com");
        ExchangeClient exchangeClient = new ExchangeClient.ExchangeClientBuilder()
                .hostname(HOSTNAME)
                .exchangeVersion(ExchangeVersion.Exchange2010)
                .username(USERNAME)
                .password(PASSWORD)
                .subject("xxx通知")
                .message(builder.toString())
                .recipientToList(fasong)
                .attachments(attachments)
                .recipientBcc(screct)
                .build();
        exchangeClient.sendExchange();
    }
}

Java中使用Exchange Online发送邮件,你可以使用JavaMail API来完成。下面是一个简单的示例代码: ```java import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class ExchangeOnlineEmailSender { public static void main(String[] args) { // 配置SMTP服务器和认证信息 Properties props = new Properties(); props.put("mail.smtp.host", "smtp.office365.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // 设置发件人邮箱和密码 final String username = "your_email@your_domain.com"; final String password = "your_password"; // 创建会话 Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(username, password); } }); try { // 创建邮件消息 Message message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress("your_email@your_domain.com")); // 设置收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient_email@recipient_domain.com")); // 设置邮件主题 message.setSubject("Hello from JavaMail"); // 设置邮件正文 message.setText("This is a test email from JavaMail API"); // 发送邮件 Transport.send(message); System.out.println("Email sent successfully!"); } catch (MessagingException e) { e.printStackTrace(); } } } ``` 请注意,你需要将代码中的`your_email@your_domain.com`替换为你的发件人邮箱地址,`your_password`替换为你的邮箱密码,`recipient_email@recipient_domain.com`替换为接收邮件的收件人邮箱地址。 此代码使用SMTP协议通过Exchange Online发送邮件。它会连接到Office 365的SMTP服务器,并使用提供的用户名和密码进行身份验证。确保你已经启用了Exchange Online中的SMTP并拥有有效的SMTP凭据。 此外,确保你已经包含了JavaMail API库,可以从JavaMail官方网站下载并添加到你的项目中。 希望对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值