用Java mail实现Exchange发邮件
创始人
2024-03-24 05:53:03
0

文章目录

  • 1. 官方指导文章
  • 2. 需要用到com.microsoft.ews-java-api
    • 2.1 maven中添加
    • 2.2 gradle中添加
  • 3. 完整代码:新建一个MailUtil.java类:

1. 官方指导文章

官方文章:https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide

Creating a Recurring Appointment
To schedule a recurring appointment, create an appointment for the first meeting time, and choose ‘Recurrence.’ Outlook will use your initial appointment as a start date. Set the end date by specifying a date for the recurring appointments to end or a number of occurrences for this recurring appointment. You can also specify no end date. If the meeting will occur on more than one day of the week, choose the days on which the meeting/appointment will occur. You can use the EWS JAVA API to create a recurring appointment, as shown in the following code.

Appointment appointment = new Appointment(service);
appointment.setSubject(“Recurrence Appointment for JAVA XML TEST”);
appointment.setBody(MessageBody.getMessageBodyFromText(“Recurrence Test Body Msg”));

SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date startDate = formatter.parse(“2010-05-22 12:00:00”);
Date endDate = formatter.parse(“2010-05-22 13:00:00”);

appointment.setStart(startDate);//new Date(2010-1900,5-1,20,20,00));
appointment.setEnd(endDate); //new Date(2010-1900,5-1,20,21,00));

formatter = new SimpleDateFormat(“yyyy-MM-dd”);
Date recurrenceEndDate = formatter.parse(“2010-07-20”);

appointment.setRecurrence(new Recurrence.DailyPattern(appointment.getStart(), 3));

appointment.getRecurrence().setStartDate(appointment.getStart());
appointment.getRecurrence().setEndDate(recurrenceEndDate);
appointment.save();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Availability Service
The EWS Java API makes it very easy to consume the Availability service. The Availability service makes it possible to retrieve free/busy information for users for whom the caller does not necessarily have access rights. It also provides meeting time suggestions.

The following example shows how to call the Availability service by using the EWS Java API.

// Create a list of attendees for which to request availability
// information and meeting time suggestions.

List attendees = new ArrayList();
attendees.add(new AttendeeInfo(“test@contoso.com”));
attendees.add(new AttendeeInfo(“temp@contoso.com”));

SimpleDateFormat formatter = new SimpleDateFormat(“yyyy/MM/dd”);

//minimum time frame allowed by API is 24 hours
Date start = formatter.parse(“2010/05/18”);
Date end = formatter.parse(“2010/05/19”);

// Call the availability service.
GetUserAvailabilityResults results = service.getUserAvailability(
attendees,
new TimeWindow(start, end),
AvailabilityData.FreeBusyAndSuggestions);

// Output attendee availability information.
int attendeeIndex = 0;

for (AttendeeAvailability attendeeAvailability : results.getAttendeesAvailability()) {
System.out.println(“Availability for " + attendees.get(attendeeIndex));
if (attendeeAvailability.getErrorCode() == ServiceError.NoError) {
for (CalendarEvent calendarEvent : attendeeAvailability.getCalendarEvents()) {
System.out.println(“Calendar event”);
System.out.println(” Start time: " + calendarEvent.getStartTime().toString());
System.out.println(" End time: " + calendarEvent.getEndTime().toString());

		if (calendarEvent.getDetails() != null){System.out.println("  Subject: " + calendarEvent.getDetails().getSubject());// Output additional properties.}}
}attendeeIndex++;

}

// Output suggested meeting times.
for (Suggestion suggestion : results.getSuggestions()) {
System.out.println("Suggested day: " + suggestion.getDate().toString());
System.out.println("Overall quality of the suggested day: " + suggestion.getQuality().toString());

for (TimeSuggestion timeSuggestion : suggestion.getTimeSuggestions()) {System.out.println("  Suggested time: " + timeSuggestion.getMeetingTime().toString());System.out.println("  Suggested time quality: " + timeSuggestion.getQuality().toString());// Output additonal properties.
}

}

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
Using pull notifications with the EWS JAVA API
The following example shows how to subscribe to pull notifications and how to retrieve the latest events.

// Subscribe to pull notifications in the Inbox folder, and get notified when a new mail is received, when an item or folder is created, or when an item or folder is deleted.

List folder = new ArrayList();
folder.add(new FolderId().getFolderIdFromWellKnownFolderName(WellKnownFolderName.Inbox));

PullSubscription subscription = service.subscribeToPullNotifications(folder,5
/* timeOut: the subscription will end if the server is not polled within 5 minutes. /, null / watermark: null to start a new subscription. */, EventType.NewMail, EventType.Created, EventType.Deleted);

// Wait a couple minutes, then poll the server for new events.
GetEventsResults events = subscription.getEvents();

// Loop through all item-related events.
for(ItemEvent itemEvent : events.getItemEvents()) {
if (itemEvent.getEventType()== EventType.NewMail) {
EmailMessage message = EmailMessage.bind(service, itemEvent.getItemId());
} else if(itemEvent.getEventType()==EventType.Created) {
Item item = Item.bind(service, itemEvent.getItemId());
} else if(itemEvent.getEventType()==EventType.Deleted) {
break;
}
}

// Loop through all folder-related events.
for (FolderEvent folderEvent : events.getFolderEvents()) {
if (folderEvent.getEventType()==EventType.Created) {
Folder folder = Folder.bind(service, folderEvent.getFolderId());
} else if(folderEvent.getEventType()==EventType.Deleted) {
System.out.println("folder deleted”+ folderEvent.getFolderId.UniqueId);
}
}

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
如果你不想看上面的文章,可以直接跳过到下面

2. 需要用到com.microsoft.ews-java-api

microsoft.exchange.webservices

导入ews-java-api-2.0.jar, 在pom.xml文件里加入以下代码:

2.1 maven中添加

com.microsoft.ews-java-apiews-java-api2.0

1
2
3
4
5

2.2 gradle中添加

Gradle
dependencies {
compile ‘com.microsoft.ews-java-api:ews-java-api:2.0’
}
1
2
3
4

3. 完整代码:新建一个MailUtil.java类:

package com.spacex.util;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

/**

  • 邮件发送工具实现类

  • @author python & basketball

  • @create 2017/01/05
    */
    public class MailUtil {

    private static Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**

    • 发送邮件

    • @param mail

    • @return
      */
      public static boolean sendEmail() {

      Boolean flag = false;
      try {
      ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //新建server版本
      ExchangeCredentials credentials = new WebCredentials(“vino”, “abcd123”, “spacex”); //用户名,密码,域名
      service.setCredentials(credentials);
      service.setUrl(new URI(“https://outlook.spacex.com/EWS/Exchange.asmx”)); //outlook.spacex.com 改为自己的邮箱服务器地址
      EmailMessage msg = new EmailMessage(service);
      msg.setSubject(“This is a test!”); //主题
      msg.setBody(MessageBody.getMessageBodyFromText(“this is a test! pls ignore it!”)); //内容
      msg.getToRecipients().add(“126@126.com”); //收件人
      // msg.getCcRecipients().add(“test2@test.com”); //抄送人
      // msg.getAttachments().addFileAttachment(“D:\Downloads\EWSJavaAPI_1.2\EWSJavaAPI_1.2\Getting started with EWS Java API.RTF”); //附件
      msg.send(); //发送
      flag = true;
      } catch (Exception e) {
      e.printStackTrace();
      }

      return flag;

    }

    public static void main(String[] args) {

     sendEmail();
    

    }
    }

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
以上为全部代码,有任何问题可以联系我!

相关内容

热门资讯

望城最新政策!即征即奖! 即征即奖政策解读 一、活动对象: 望城区2025年3月1日以后履行拆房腾地义务的拆迁安置补偿对象。 ...
流动摊贩违规添加食品添加剂,公... 极目新闻通讯员 王粲 以公开促公正、以听证赢公信,近日,湖北省团风县检察院就甄某销售不合格食品行政公...
浙江义乌首创商会退出机制 制度... 中新网义乌12月27日电 题:浙江义乌首创商会退出机制 制度化探索获全国推广 作者 董易鑫 “我们正...
《办法》:建立身份透明制度,划... 专家解读|促进人工智能拟人化互动服务有序开展引领人工智能负责任创新 人工智能技术的突破正推动人机交互...
探寻强制执行律师服务,周云卿律... 在法律纠纷中,胜诉只是第一步,真正实现权益落地,强制执行环节至关重要。那么,强制执行律师服务哪家强?...
李宏毅直播称活动因不可抗力取消... 12月25日,艺人李宏毅因与芒果娱乐的经纪合同纠纷,被法院执行约1118万元款项,同时收到限制消费令...
法援故事|法援“撑腰”!13名... 绿色通道,法援接单 春节前,农民工们多次向县住建局清欠办反映情况,在工作人员协调下,郭某某给部分人出...
山西黄河壶口瀑布旅游区推出免门... 公众号转载山西经济日报稿件,须申请授权。 山西黄河壶口瀑布旅游区日前发布消息,从12月下旬至明年2...