最近,我开始了一项任务,使用javamail API检索交换服务器上的电子邮件。但是,有时我无法获取邮件,因为Outlook客户端与邮件服务器同步,因此这些邮件将从服务器中删除。 有什么方法可以确保我可以在Outlook同步之前或之后获取所有新电子邮件。或者我应该尝试连接到Outlook,如果有,是否有任何可用的免费API?谢谢。如何从outlook中读取电子邮件
0
A
回答
1
是不是可以将outlook配置为在服务器上留下消息的副本?我真的不认为与前景的联系是可行的。
0
我有解决方案从Outlook读取电子邮件。 我们需要提供用户名,密码,域名和交换地址:https://webmail.**companynameXYZ**.com/ews/exchange.asmx
。
以下是代码....我使用这个从某种目的,从未读邮件下载附件,使其成为下载后读取。 注:我们需要的DLL Microsoft.Exchange.WebServices.dll在C#中下载
CODE:
string _username = string.Empty;
string _password = string.Empty;
string _domain = "us";
string _exchange = string.Empty;
_username = ConfigurationSettings.AppSettings["Username"].ToString();
_password = ConfigurationSettings.AppSettings["Pasword"].ToString();
_exchange = ConfigurationSettings.AppSettings["MailServer"].ToString();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
// service.AutodiscoverUrl("[email protected]");
service.Url = new Uri(_exchange);
service.Credentials = new WebCredentials(_username, _password, _domain);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
int attachmentCount = 0;
foreach (Item item in findResults.Items)
{
// Bind to an existing message item, requesting its Id property plus its attachments collection.
EmailMessage message = EmailMessage.Bind(service, item.Id);
//read only unread mails and has attachemnts to it.
if ((!message.IsRead) && message.HasAttachments)
{
Console.WriteLine(item.Subject);
#region Iterate through the attachments collection and load each attachment.
foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
attachmentCount++;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
Console.WriteLine("Attachment name: " + fileAttachment.Name);
//create Attachments-folder if not exists.
if (!Directory.Exists(@"C:\Attachments\"))
{
Directory.CreateDirectory(@"C:\Attachments\");
}
// Load attachment contents into a file.
fileAttachment.Load("C:\\attachments\\" + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load();
Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
}
}//for inner
#endregion
//mark as READ
message.IsRead = true;
message.Update(ConflictResolutionMode.AlwaysOverwrite);
Console.WriteLine("------------------------");
}//if
}//for outer
0
微软团队已经创建EWS-Java的API(Java实现)作为到替代Microsoft.Exchange.WebServices.dll为C#实现,而好处是它的开源:
0
Java代码:
package EWSGetDetailsOffice365;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentSchema;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Folder;
import microsoft.exchange.webservices.data.IAutodiscoverRedirectionUrl;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.ServiceLocalException;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;
public class MSExchangeEmailService {
public static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl {
public boolean autodiscoverRedirectionUrlValidationCallback(String redirectionUrl) {
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
private static ExchangeService service;
private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched.
/**
* Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
* is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
*/
static{
try{
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the Exchange Credentials.
* Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
*/
public MSExchangeEmailService() {
service.setCredentials(new WebCredentials("[email protected]", "1234"));
try {
service.autodiscoverUrl("[email protected]", new RedirectionUrlCallback());
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
service.setTraceEnabled(true);
}
/**
* Reading one email at a time. Using Item ID of the email.
* Creating a message data map as a return value.
*/
public Map readEmailItem(ItemId itemId){
Map messageData = new HashMap();
try{
Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
messageData.put("emailItemId", emailMessage.getId().toString());
messageData.put("subject", emailMessage.getSubject().toString());
messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString());
messageData.put("senderName",emailMessage.getSender().getName().toString());
Date dateTimeCreated = emailMessage.getDateTimeCreated();
messageData.put("SendDate",dateTimeCreated.toString());
Date dateTimeRecieved = emailMessage.getDateTimeReceived();
messageData.put("RecievedDate",dateTimeRecieved.toString());
messageData.put("Size",emailMessage.getSize()+"");
messageData.put("emailBody",emailMessage.getBody().toString());
}catch (Exception e) {
e.printStackTrace();
}
return messageData;
}
/**
* Number of email we want to read is defined as NUMBER_EMAILS_FETCH,
*/
public List readEmails(){
List msgDataList = new ArrayList();
try{
Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
int i =1;
for (Item item : results){
Map messageData = new HashMap();
messageData = readEmailItem(item.getId());
System.out.println("\nEmails #" + (i++) + ":");
System.out.println("subject : " + messageData.get("subject").toString());
System.out.println("Sender : " + messageData.get("senderName").toString());
msgDataList.add(messageData);
}
}catch (Exception e) {
e.printStackTrace();
}
return msgDataList;
}
/**
* Reading one appointment at a time. Using Appointment ID of the email.
* Creating a message data map as a return value.
*/
public Map readAppointment(Appointment appointment){
Map appointmentData = new HashMap();
try {
appointmentData.put("appointmentItemId", appointment.getId().toString());
appointmentData.put("appointmentSubject", appointment.getSubject());
appointmentData.put("appointmentStartTime", appointment.getStart()+"");
appointmentData.put("appointmentEndTime", appointment.getEnd()+"");
//appointmentData.put("appointmentBody", appointment.getBody().toString());
} catch (ServiceLocalException e) {
e.printStackTrace();
}
return appointmentData;
}
/**
*Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
* Here I also considered the start data and end date which is a 30 day span.
* We need to set the CalendarView property depending upon the need of ours.
*/
public List readAppointments(){
List apntmtDataList = new ArrayList();
Calendar now = Calendar.getInstance();
Date startDate = Calendar.getInstance().getTime();
now.add(Calendar.DATE, 30);
Date endDate = now.getTime();
try{
CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
CalendarView cView = new CalendarView(startDate, endDate, 5);
cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties as well depending upon our need.
//FindItemsResults appointments = calendarFolder.findAppointments(cView);
FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView);
System.out.println("|------------------> Appointment count = " + appointments.getTotalCount());
int i =1;
//List appList = appointments.getItems();
for (Appointment appointment : appointments.getItems()) {
System.out.println("\nAPPOINTMENT #" + (i++) + ":");
Map appointmentData = new HashMap();
appointmentData = readAppointment(appointment);
System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
apntmtDataList.add(appointmentData);
}
}catch (Exception e) {
e.printStackTrace();
}
return apntmtDataList;
}
public static void getAllMeetings() throws Exception {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2016-01-01 00:00:00");
SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime,startDate);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, filter, new ItemView(1000));
System.out.println("|------------------> meetings count = " + findResults.getTotalCount());
for (Item item : findResults.getItems())
{
Appointment appt = (Appointment)item;
//appt.setStartTimeZone();
System.out.println("TimeZone====="+appt.getTimeZone());
System.out.println("SUBJECT====="+appt.getSubject());
System.out.println("Location========"+appt.getLocation());
System.out.println("Start Time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Last Modified Time========"+appt.getLastModifiedName());
System.out.println("*************************************************\n");
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static void main(String[] args) {
MSExchangeEmailService msees = new MSExchangeEmailService();
//msees.readEmails();
//msees.readAppointments();
try {
msees.getAllMeetings();
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
相关问题
- 1. 如何从Clutter outlook文件夹中读取电子邮件C#
- 2. 从本地电脑的Outlook中读取电子邮件
- 3. 如何从Outlook电子邮件中提取互联网电子邮件标题?
- 4. 从Outlook子文件夹读取电子邮件
- 5. C# - 从Outlook中的非默认帐户读取电子邮件
- 6. 从asp.net中的其他服务器读取Outlook电子邮件
- 7. 从outlook通过powershell读取MSG文件..如何获取电子邮件地址?
- 8. 如何读取从当前的电子邮件的电子邮件签名在Outlook插件形式的区域?
- 9. 如何从outlook中获取电子邮件地址?
- 10. 如何从Outlook 2007中获取发送电子邮件地址
- 11. 如何从Outlook 2007中提取电子邮件的内容?
- 12. 从C#读取Outlook邮件#
- 13. 如何从Outlook中使用javax.mail pop3获取未读电子邮件
- 14. 如何从Outlook获取发件人的电子邮件地址?
- 15. AccessViolationException读取Outlook 2007中的电子邮件发件人
- 16. 使用VBA从Outlook电子邮件正文中提取电子邮件地址?
- 17. 如何使用Excel VBA读取Outlook中的共享电子邮件中的电子邮件
- 18. 如何从回复中获取/读取电子邮件ID
- 19. 如何从MS Outlook 2010获取电子邮件地址?
- 20. 读取多个Outlook电子邮件在C#中
- 21. microsoft outlook如何从我属于的电子邮件组发送电子邮件?
- 22. Excel VBA代码从底部的收件箱中读取Outlook电子邮件
- 23. C#:如何查看Outlook电子邮件
- 24. 如何从Outlook中的电子邮件正文提取电话号码?
- 25. Android,从SDK读取电子邮件
- 26. 从Outlook电子邮件中提取msg附件
- 27. 获取outlook电子邮件的属性
- 28. 从MS Outlook的未读电子邮件下载附件
- 29. 在Outlook中读取Outlook邮件
- 30. 如何从Outlook REST API中的特定电子邮件地址获取电子邮件?
感谢您的回复,有很多邮件大附件的每一天的到来,我恐怕就会变成一个的chanllenge到服务器。 – user737570 2011-05-04 08:41:21
如何在Outlook中配置邮件规则将邮件移动到其他文件夹(但将其保留在服务器上),您可以处理该文件夹中的所有邮件,并在处理它们后将其从服务器中删除? – Pleun 2011-05-04 14:23:06
@Pleun,你的意思是Outlook文件夹?如何从Outlook收件箱文件夹读取? – 2012-01-05 14:52:02