Java实战-用Java mail实现Exchange发邮件给你喜欢的人

news/2024/11/14 13:15:09/

目录

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

如何用java mail 实现Exchange发邮件的功能

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();

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<AttendeeInfo> attendees = new ArrayList<AttendeeInfo>();
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.}
}

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);}
}

如果你不想看上面的文章,可以直接跳过到下面

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

microsoft.exchange.webservices

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

2.1 maven中添加

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

2.2 gradle中添加

Gradle
dependencies {compile 'com.microsoft.ews-java-api:ews-java-api:2.0'
}

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();}
}

以上为全部代码,有任何问题可以联系我!

请参照:

https://stackoverflow.com/questions/1713116/javamail-exchange-authentication/41529188#41529188

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


http://www.ppmy.cn/news/937.html

相关文章

Redis常见问题

1 为什么使用Redis Redis是No-SQL&#xff08;Not Only SQL&#xff09;的一种&#xff0c;目前最火的一种非关系型数据库 基于内存存储&#xff0c;支持多种数据类型&#xff0c;键值对存储&#xff0c;Java开发主要面向服务端&#xff0c;就需要抗并发量&#xff0c;性能 …

【Java难点攻克】「Guava RateLimiter」针对于限流器的入门到实战和源码原理分析

限流器的思路和算法 如果让你来造一个限流器&#xff0c;有啥想法&#xff1f; 漏桶算法 用一个固定大小的队列。比如设置限流为5qps&#xff0c;1s可以接受5个请求&#xff1b;那我们就造一个大小为5的队列&#xff0c;如果队列为满了&#xff0c;就拒绝请求&#xff1b;如…

第十三章 DFS与BFS(保姆级教学!!超级详细的图示!!)

第十三章 DFS与BFS一、深度优先搜索1、什么是DFS&#xff1f;2、DFS代码模板&#xff08;1&#xff09;问题&#xff1a;&#xff08;2&#xff09;分析&#xff1a;&#xff08;3&#xff09;模板&#xff1a;3、DFS代码分析二、广度优先搜索1、什么是BFS&#xff1f;2、BFS代…

远程办公:通过cpolar内网穿透,远程桌面控制家里公司内网电脑

疫情反反复复的当下&#xff0c;有时候会遇到需要居家办公的情况&#xff0c;但在办公室的电脑上仍有很多重要资料需要存取&#xff0c;且办公室所在的局域网中也有很多相关资源需要被访问&#xff08;如文件共享服务器、OA系统等&#xff09;。如何能在家通过远程处理好办公事…

vue.js父组件访问子组件

父组件访问子组件 有时候我们需要父组件直接访问子组件&#xff0c;子组件直接访问父组件&#xff0c;或者是子组件访问跟组件。 父组件访问子组件&#xff1a;使用$children或refs子组件访问父组件&#xff1a;使用$parent 代码 <!DOCTYPE html> <html><he…

[附源码]计算机毕业设计仓库管理系统Springboot程序

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

关于PCB布局布线,这篇文章说透了

关于PCB布局布线的问题&#xff0c;今天我们不讲信号完整性分析&#xff08;SI&#xff09;、电磁兼容性分析&#xff08;EMC&#xff09;、电源完整性分析&#xff08;PI&#xff09;。 只讲可制造性分析&#xff08;DFM) &#xff0c;可制造性设计不合理同样会导致产品设计失…

基础生态学名词解释

生态学(ecology)&#xff1a;是研究有机体及其周围环境-包括非生物环境和生物环境相互关系的科学。 生态学的研究方法&#xff1a;野外的、实验的、理论的 环境&#xff08;environment&#xff09;&#xff1a;是指某一特定生物体或生物群体 生活空间的外界自然条件的总和。…