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

news2024/9/30 9:27:55

目录

  • 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.coloradmin.cn/o/55139.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

设计模式(下)

四、行为型模式 4.1 模板方法模式 4.1.1 概述 在面向对象程序设计过程中&#xff0c;程序员常常会遇到这种情况&#xff1a;设计一个系统时知道了算法所需的关键步骤&#xff0c;而且确定了这些步骤的执行顺序&#xff0c;但某些步骤的具体实现还未知&#xff0c;或者说某些…

swin Transformer

文章目录swin Transformer创新点&#xff1a;网络架构&#xff1a;Patch Partitionlinear EmbeddingSwin TransformerPatch Merging总结swin Transformer 论文&#xff1a;https://arxiv.org/pdf/2103.14030.pdf 代码&#xff1a;https://github.com/microsoft/Swin-Transfor…

基于FDB方法的供给需求优化算法改进——基于工程设计问题的综合研究

&#x1f468;‍&#x1f393;个人主页&#xff1a;研学社的博客 &#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜…

校园网页设计成品 学校班级网页制作模板 dreamweaver网页作业 简单网页课程成品 大学生静态HTML网页源码

&#x1f389;精彩专栏推荐 &#x1f4ad;文末获取联系 ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 &#x1f482; 作者主页: 【主页——&#x1f680;获取更多优质源码】 &#x1f393; web前端期末大作业&#xff1a; 【&#x1f4da;毕设项目精品实战案例 (10…

ArangoDB简单入门

一、安装与启动 1、进入到某个目录 cd /home/neunhoef/ 2 获取包 wget https://download.arangodb.com/arangodb34/Community/Linux/arangodb3-linux-3.4.1.tar.gz 3、解压 tar xzvf arangodb3-linux-3.4.1.tar.gz 4、将使用的命令放到path中 export PATH"/home/neunhoef…

Ajax学习:原生jsonp实践

输入内容&#xff1a;丧失焦点 向服务器发送请求 对用户名做是否存在的检测 并且改变框的颜色 服务端&#xff1a; const {json } require(express); const express require(express)const app express(); app.get(/home, function(requset, response) {//设置响应头 名称…

分布式全局唯一ID (学习总结---从入门到深化)

目录 分布式全局唯一ID 何为 ID 为什么需要分布式ID 分布式全局唯一ID解决方案 UUID 依靠数据库自增字段生成 号段模式 Redis自增key方案 雪花算法&#xff08;SnowFlake&#xff09; 分布式全局唯一ID_什么是雪花算法SonwFlake 雪花算法作用 SnowFlake算法优点 SnowFlake…

【flutter-mobx】Flutter 状态管理- 使用 MobX实现计数器

实践flutter mobx&#xff1a; 提示&#xff1a;对下面这篇掘金文章的实践&#xff0c;通过flutter结合 mobx 实现计数器&#xff0c;过程中也添加了一些处理和注释&#xff0c;代码放在feat/mobx下 https://juejin.cn/post/6954523549386162213 https://github.com/ThinkerW…

论算法是如何优化的:四数之和

论算法是如何优化的&#xff1a;四数之和 心路历程 闲来无事&#xff0c;刷刷力扣&#xff0c;突然看到一道题目叫做四数之和&#xff0c;难度中等&#xff0c;心想&#xff0c;这不就是我大显身手的时候了吗&#xff1f;&#xff1f;&#xff1f;我直接就是一个点击进入&…

2022 CMU15-445 Project 1 Buffer Pool

通过截图 Task #1 - Extendible Hash Table 该 task 的知识点名为 可扩展动态散列 https://cloud.tencent.com/developer/article/1020586 这个部分要实现一个 extendible 哈希表&#xff0c;内部不可以用 built-in 的哈希表&#xff0c;比如 unordered_map。这个哈希表在 Buf…

Open-Dis的C++版本编译(CMake-gpu 3.21.4)以及SDL2和SDL_net库的配置使用

目录Open-DisOpen-Dis简介分布式交互仿真更多资料Open-Dis下载CMake编译教程SDL2和SDL_netSDL介绍下载SDL配置SDL2下载SDL_net配置SDL_net工程编译Open-DisOpen-Dis Open-Dis简介 Dis是国防部&#xff0c;北约和联合国实时/虚拟世界建模和仿真中使用最广泛的协议之一。 Open-…

关于二进制

关于二进制 读《程序是怎样跑起来的》 用二进制表示计算机信息的原因 计算机内部是由IC&#xff08;集成电路&#xff09;这种电子部件构成的。CPU和内存也是IC的一种&#xff0c;IC有几种不同的形状&#xff0c;有的像一条黑色的蜈蚣&#xff0c;在其两侧有数个乃至数百个引脚…

智慧水务:数字孪生污水处理厂,3D可视化一键管控

近年来&#xff0c;智慧水务、数字水务成为水务行业的热点领域。对于污水处理领域&#xff0c;如何贯彻落实双碳战略&#xff0c;积极推进智慧水厂建设&#xff0c;显得尤为关键。 可视化技术结合视频融合、BIM、5G、物联网、云计算及大数据等先进技术&#xff0c;围绕水质达标…

用DIV+CSS技术制作个人博客网站(web前端网页制作课期末作业)

&#x1f389;精彩专栏推荐 &#x1f4ad;文末获取联系 ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 &#x1f482; 作者主页: 【主页——&#x1f680;获取更多优质源码】 &#x1f393; web前端期末大作业&#xff1a; 【&#x1f4da;毕设项目精品实战案例 (10…

【Docker】搭建MySQL主从复制,详细的图文展示

Docker是基于Go语言实现的云开源项目。Docker的主要目标是**“Build&#xff0c;Ship and Run Any App,Anywhere”**。也就是通过对应用组件的封装、分发、部署、运行等生命周期的管理&#xff0c;使用户的APP&#xff08;可以是一个WEB应用或数据库应用等等&#xff09;及其运…

[附源码]JAVA毕业设计计算机散件报价系统(系统+LW)

[附源码]JAVA毕业设计计算机散件报价系统&#xff08;系统LW&#xff09; 目运行 环境项配置&#xff1a; Jdk1.8 Tomcat8.5 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技…

技巧 | Python绘制2022年卡塔尔世界杯决赛圈预测图

文章目录&#x1f3f3;️‍&#x1f308; 1. 世界杯三十二强&#x1f3f3;️‍&#x1f308; 2. 世界杯十六强&#x1f3f3;️‍&#x1f308; 3. 世界杯八强&#x1f3f3;️‍&#x1f308; 4. 世界杯四强&#x1f3f3;️‍&#x1f308; 5. 决赛圈&#x1f3f3;️‍&#x1f…

技术内幕 | 阿里云EMR StarRocks 极速数据湖分析

作者&#xff1a;阿里云智能技术专家 周康&#xff0c;StarRocks Active Contributor 郑志铨&#xff08;本文为作者在 StarRocks Summit Asia 2022 上的分享&#xff09; 为了能够满足更多用户对于极速分析数据的需求&#xff0c;同时让 StarRocks 强大的分析能力应用在更加广…

【温故而知新】构建高可用Linux服务器(三)

时间&#xff1a;2022年12月02日 作者&#xff1a;小蒋聊技术 邮箱&#xff1a;wei_wei10163.com 微信&#xff1a;wei_wei10 前言 大家好&#xff0c;欢迎来到小蒋聊技术。小蒋准备和大家一起聊聊技术的那些事。 今天小蒋继续坚持“温故而知新”的落地实践&#xff0c;继续…

[附源码]计算机毕业设计影院管理系统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…