Java实现调用公司Exchange发送邮件(Outlook)

什么是Exchange

????Exchange Server是微软公司的一套电子邮件服务组件。它支持多种电子邮件网络协议,如:SMTP、POP3、IMAP4。Exchange Server是个消息与协作系统,可以被用来架构应用于企业、学校的邮件系统甚至于免费邮件系统,也可以用于开发工作流。

Exchange特别之处

????传统的电子邮箱,像QQ邮箱、163邮箱,用的都是SMTP协议来发送邮件,POP3/IMAP来收取邮件,这些协议都是早期公开的邮件通信协议,至今都被广泛地使用,网上有很多方案和技术文档。
????而Exchange邮箱使用的是微软自己定制的Exchange ActiveSync协议,这套协议兼容SMTP、POP3、IMAP4等多种电子邮件协议,因此能够与其他邮箱进行邮件通信,但这套协议是微软所定制的,所以不能像其他邮箱那样调用SMTP来直接发送邮件,必须调用微软所给出的接口,微软基于Java给出了一套单独的接口。

添加jar包

1
2
3
4
5
<dependency>
    <groupId>com.microsoft.ews-java-api</groupId>
    <artifactId>ews-java-api</artifactId>
    <version>2.0</version>
</dependency>

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;

/**
 *
 * microsoft发送邮件工具类
 * @author shi
 * @date 2019/10/30
 *
 **/
public class ExchangeMailUtil {
   
    //邮件服务器地址
    private String mailServer;
    //用户名
    private String user;
    //密码
    private String password;
    //使用的方式,默认可用不填
    private String domain;

    /**
     * 构造方法
     */
    public ExchangeMailUtil(String mailServer, String user, String password) {
        this.mailServer = mailServer;
        this.user = user;
        this.password = password;
    }
   
    /**
     * 构造方法
     */
    public ExchangeMailUtil(String mailServer, String user, String password, String domain) {
        this.mailServer = mailServer;
        this.user = user;
        this.password = password;
        this.domain = domain;
    }
   
    /**
     * 创建邮件服务
     *
     * @return 邮件服务
     */
    private ExchangeService getExchangeService() {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        //用户认证信息
        ExchangeCredentials credentials;
        if (domain == null) {
            credentials = new WebCredentials(user, password);
        } else {
            credentials = new WebCredentials(user, password, domain);
        }
        service.setCredentials(credentials);
        try {
            service.setUrl(new URI(mailServer));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return service;
    }

    /**
     * 收取邮件
     *
     * @param max 最大收取邮件数
     * @throws Exception
     */
    public ArrayList<EmailMessage> receive(int max) throws Exception {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        ExchangeCredentials credentials = new WebCredentials(user, password);
        service.setCredentials(credentials);
        service.setUrl(new URI(mailServer));
        //绑定收件箱,同样可以绑定发件箱
        Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
        //获取文件总数量
        int count = inbox.getTotalCount();
        if (max > 0) {
            count = count > max ? max : count;
        }
        //循环获取邮箱邮件
        ItemView view = new ItemView(count);
        FindItemsResults<Item> findResults = service.findItems(inbox.getId(), view);
        ArrayList<EmailMessage> result = new ArrayList<>();
        for (Item item : findResults.getItems()) {
            EmailMessage message = EmailMessage.bind(service, item.getId());
            result.add(message);
        }
        return result;
    }

    /**
     * 收取所有邮件
     * @throws Exception
     */
    public ArrayList<EmailMessage> receive() throws Exception {
        return receive(0);
    }

    /**
     * 发送带附件的mail
     * @param subject 邮件标题
     * @param to 收件人列表
     * @param cc 抄送人列表
     * @param bodyText 邮件内容
     * @param attachmentPaths 附件地址列表
     * @throws Exception
     */
    public void send(String subject, String[] to, String[] cc, String bodyText, String[] attachmentPaths)throws Exception {
        ExchangeService service = getExchangeService();
        EmailMessage msg = new EmailMessage(service);
        msg.setSubject(subject);
        MessageBody body = MessageBody.getMessageBodyFromText(bodyText);
        body.setBodyType(BodyType.HTML);
        msg.setBody(body);
        for (String toPerson : to) {
            msg.getToRecipients().add(toPerson);
        }
        if (cc != null) {
            for (String ccPerson : cc) {
                msg.getCcRecipients().add(ccPerson);
            }
        }
        if (attachmentPaths != null) {
            for (String attachmentPath : attachmentPaths) {
                msg.getAttachments().addFileAttachment(attachmentPath);
            }
        }
        msg.send();
    }
   
    /**
     * 发送不带抄送人的邮件
     * @param subject 标题
     * @param to 收件人列表
     * @param bodyText 邮件内容
     * @throws Exception
     */
    public void send(String subject,String[] to,String bodyText) throws Exception {
        send(subject, to, null, bodyText);
    }
   
    /**
     * 发送不带附件的mail
     * @param subject 邮件标题
     * @param to 收件人列表
     * @param cc 抄送人列表
     * @param bodyText 邮件内容
     * @throws Exception
     */
    public void send(String subject, String[] to, String[] cc, String bodyText) throws Exception {
        send(subject, to, cc, bodyText, null);
    }
}

测试方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
     * 发送邮件主方法
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // Outlook Web Access路径通常为/EWS/exchange.asmx
        ExchangeMailUtil mailUtil = new ExchangeMailUtil("https://mail.xxxxxxxx.com/ews/exchange.asmx", "username",
                "123456");
        //接收人
        String[] to = mailUtil.removeArrayEmpty(new String[]{"[email protected]"});
        //抄送人
        String[] cc = mailUtil.removeArrayEmpty(new String[]{"[email protected]"});
        // 发送邮件
        mailUtil.send("Subject", to, cc, "content");
    }

附:官方文档地址

https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide