exchange 发送邮件

package com.example.demo.test;


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


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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;
/**
 * exchange协议发送邮件
 * @author peter
 *
 */
public class ExchangeClient {

   private static Log log = LogFactory.getLog(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;
        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;
        }

        /**
         * The recipient for this send.
         *
         * @param recipientTo the recipient for this send.
         * @return the builder for chain usage.
         */
        public ExchangeClientBuilder recipientTo(String recipientTo) {
            this.recipientTo = Arrays.asList(recipientTo.split(","));
            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) {
            log.info("An exception occured 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) {
            log.info("An exception occured while setting the email message.", ex);
            return false;
        }

        // TO recipient.
        for(String recipient : recipientTo){
           try {
                emailMessage.getToRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the TO recipient(" + recipientTo + ").", ex);
                return false;
            }
        }

        // CC recipient.
        for (String recipient : recipientCc) {
            try {
                emailMessage.getCcRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the CC recipient(" + recipient + ").", ex);
                return false;
            }
        }

        // BCC recipient
        for (String recipient : recipientBcc) {
            try {
                emailMessage.getBccRecipients().add(recipient);
            } catch (ServiceLocalException ex) {
                log.info("An exception occured while sstting the BCC recipient(" + recipient + ").", ex);
                return false;
            }
        }

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

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

        return true;
    }

}

调用代码

package com.example.demo.test;

import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.springframework.beans.factory.annotation.Autowired;

public class ExchangeEmail {


    @Autowired
    public SendEmailUtil emailUtil;

    private static String account = "xxxxxxx@outlook.com";
    private static String pass = "xxxxxxxxx";
    private static String host = "outlook.office365.com";

    public static void main(String[] args) {
        ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                .hostname(host)
                .exchangeVersion(ExchangeVersion.Exchange2010)
                .username(account)
                .password(pass)
                .recipientTo("xxx")
                .recipientBcc("ss","ff","ddff","sef","dfe")
                .subject("Test Subject")
                .message("Test Message")
                .build();
        client.sendExchange();
    }
}

 

这是从网上找来的工具类,确认没问题。可以使用。对我需要的地方做了修改。

刚开始使用的qq的exchange服务器。ex.qq.com

发现报错ssl安全认证报错。导入认证在浏览器地址栏输入   https://ex.exmail.qq.com/EWS/exchange.asmx

具体操作 : https://blog.youkuaiyun.com/Peter_S/article/details/97649729

之后报错,请求失败,报错400.才发现qq的exchange服务器挂了。后来上网搜索了outlook邮箱。通过outlook邮箱测试。

下面这个是我搜搜outlook exchange服务器地址发现的,很有用。直接粘贴过来了。

------------------------------------------------------------------------------------

查找 Exchange 服务器名称
  如果您的电子邮件程序无法自动查找您的 Exchange ActiveSync 服务器名称,您可能需要手动查找。
  如果您连接的是 Office 365 电子邮件,请将 outlook.office365.com 用作 Exchange ActiveSync 服务器名称
  如果您正连接到 Exchange 邮箱但未使用 Office 365,或者您不确定使用的是否是 Office 365,请按照这些步骤查找您的 Exchange ActiveSync 服务器名称。
  使用 Outlook Web App 来登录到您的帐户。 有关登录帮助,请参阅登录到 Outlook Web App。
  如果您正连接到 Exchange 邮箱但未使用 Office 365,则您登录到 Outlook Web App 之后,浏览器的地址栏中将包含您的 Exchange ActiveSync 服务器名称,但不带前导 https:// 和尾部 /owa。例如,如果用于访问 Outlook Web App 的地址是 https://mail.contoso.com/owa,则您的 Exchange ActiveSync 服务器名称是mail.contoso.com。
  如果您无法使用本节前面的信息连接到您的邮箱,则可以尝试使用您可以在 Outlook Web App 选项中查看的服务器名称值。
  在 Outlook Web App 中的工具栏上,单击“设置” >“选项”>“帐户”>“我的帐户”>“POP 和 IMAP 访问的设置”。
  注意 尽管您不是在设置 POP3 帐户,但您仍将使用该值来确定您的 Exchange ActiveSync 服务器名称。
  在“POP 设置”下,查看“服务器名称”的值。
  如果“服务器名称”值为“outlook.office365.com”,则说明您的帐户在 Office 365 工作或学校帐户 中,因此您可将 outlook.office365.com 用作 Exchange 服务器名称。
  如果“服务器名称”值不是“outlook.office365.com”,您可以尝试使用选项页上列出的服务器名称。例如,如果服务器名称是 mail.contoso.com,请尝试使用 mail.contoso.com 作为您的 Exchange 服务器名称。

连接 : https://zhidao.baidu.com/question/426676191.html

--------------------------------------------------------------------------------------------------------------------

之后在客户Linux系统测试,发信报错。

The remote server returned an error: (401) Unauthorized 

这个我是账号密码写错了,所以导致的这个问题,多了空格,尴尬

### 使用Java通过Exchange服务器发送邮件 为了实现这一功能,可以采用两种主要方法:SMTP协议和Exchange Web Services (EWS)。对于SMTP方式,在配置好相应的邮箱账户设置之后,能够利用`javax.mail`库来完成操作[^1]。 #### SMTP 方法 下面是一个基于SMTP的简单例子: ```java import javax.mail.*; import javax.mail.internet.*; public class SendEmailViaSmtp { public static void main(String[] args)throws Exception{ String host="smtp-mail.outlook.com"; // Exchange Server 的 SMTP 地址 final String username="your_email@domain.com"; final String password="password"; Properties props=new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.host",host); props.put("mail.smtp.port","587"); Session session=Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username,password); } }); Message message =new MimeMessage(session); message.setFrom(new InternetAddress("from-email@example.com")); message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("to-email@example.com")); message.setSubject("Test Mail from Java App via SMTP"); message.setText("This is a test mail sent through the Exchange server using Java."); Transport.send(message); System.out.println("Mail Sent Successfully!"); } } ``` 此代码片段展示了如何创建并发送一封简单的电子邮件给指定收件人。需要注意的是,这里使用的端口号以及主机地址应当依据实际环境中的Exchange服务器设定而定。 #### EWS 方法 当涉及到更复杂的场景时,比如管理日历项、联系人或其他Office 365资源,则推荐使用EWS API。这需要引入额外依赖如ews-java-api,并遵循OAuth认证流程获取访问令牌用于身份验证过程。 以下是简化版的EWS示例代码: ```java import microsoft.exchange.webservices.data.core.ExchangeService; import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; import microsoft.exchange.webservices.data.credential.WebCredentials; import microsoft.exchange.webservices.data.property.complex.MessageBody; import microsoft.exchange.webservices.data.core.service.item.EmailMessage; // ... ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); service.setUrl(new java.net.URI("https://outlook.office365.com/EWS/Exchange.asmx")); WebCredentials credentials = new WebCredentials("username", "password"); service.setCredentials(credentials); EmailMessage msg = new EmailMessage(service); msg.setSubject("Meeting Request"); msg.setBody(MessageBody.getMessageBodyFromString("Please attend this meeting.")); msg.getToRecipients().add("attendee@example.com"); msg.send(); System.out.println("Mail Sent Using EWS."); ``` 这段程序说明了怎样借助EWS向特定接收者发出会议请求类型的邮件通知。同样地,具体的URL和服务版本号需依照目标Exchange实例的具体情况调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值