Сохранить почту в msg файле с помощью EWS API
Я использую управляемый API 1.1 для веб-служб Exchange для подключения к Exchange Server 2010, а затем узнайте о полученных новых сообщениях. Теперь я хочу сохранить копию файла .msg в папку на диске.
Я не хочу использовать какую-либо платную третью сторону для интеграции.
Любая помощь будет оценена.
Ответы
Ответ 1
Если вы счастливы сохранить в формате .eml
, это можно сделать очень просто, используя EWS и сторонние библиотеки. Файл .eml
будет содержать все ту же информацию и может быть открыт Outlook таким же образом, как и .msg(а также другими программами).
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
FileStream fs = new FileStream("c:\test.eml", FileMode.Create);
fs.Write(mc.Content, 0, mc.Content.Length);
fs.Close();
Очищенный код:
message.Load(new PropertySet(ItemSchema.MimeContent));
var mimeContent = message.MimeContent;
using (var fileStream = new FileStream(@"C:\Test.eml", FileMode.Create))
{
fileStream.Write(mimeContent.Content, 0, mimeContent.Content.Length);
}
Ответ 2
Не существует встроенной поддержки файлов MSG с использованием EWS. Это строго формат Outlook.
Спецификация MSG публикуется в http://msdn.microsoft.com/en-us/library/cc463912%28EXCHG.80%29.aspx. Это немного сложно понять, но сделать. Вам нужно будет снять все свойства сообщения, а затем сериализовать его в формате структурированного файла OLE. Это непростая задача.
В конце концов, вам, вероятно, лучше пойти с сторонней библиотекой, иначе это может быть большой задачей для выполнения.
Ответ 3
Это предложение было опубликовано как комментарий от @mack, но я думаю, что он заслуживает своего места в качестве ответа, если не по какой-либо другой причине, кроме форматирования и читаемости ответов против комментариев.
using (FileStream fileStream =
File.Open(@"C:\message.eml", FileMode.Create, FileAccess.Write))
{
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mc = message.MimeContent;
fileStream.Write(mc.Content, 0, mc.Content.Length);
}
Ответ 4
Если формат eml является опцией, а php - это использование base64_decode на Mimencontent перед сохранением файла.
Если вы используете https://github.com/Heartspring/Exchange-Web-Services-for-PHP или https://github.com/hatsuseno/Exchange-Web-Services-for-PHP нужно добавить
$newmessage->mc = $messageobj->MimeContent->_;
в строке 245 или 247.
Ответ 5
Вы можете легко получить доступ к содержимому MIME сообщения через message.MimeContent и сохранить сообщение в виде файла EML. В последних версиях Outlook (2013 и 2016 гг.) Outlook можно напрямую открывать файлы EML.
message.Load(new PropertySet(ItemSchema.MimeContent));
MimeContent mimcon = message.MimeContent;
FileStream fStream = new FileStream("c:\test.eml", FileMode.Create);
fStream.Write(mimcon.Content, 0, mimcon.Content.Length);
fStream.Close();
Если вам все равно нужно преобразовать в формат MSG, у вас есть несколько вариантов:
1) Формат файла MSG документирован - это файл OLE store (IStorage). См. https://msdn.microsoft.com/en-us/library/cc463912(v=exchg.80).aspx
2) Используйте стороннюю файловую оболочку MSG, например, файл Independentsoft: http://www.independentsoft.de/msg/index.html. Настройка всех свойств, ожидаемых Outlook, может быть сложной задачей.
3) Преобразуйте EML файл в MSG напрямую, используя Redemption:
set Session = CreateObject("Redemption.RDOSession")
set Msg = Session.CreateMessageFromMsgFile("c:\test.msg")
Msg.Import("c:\test.eml", 1024)
Msg.Save
Ответ 6
Вы можете загрузить все вложения с помощью EWS API и С#. Ниже приведен пример:
byte[][] btAttachments = new byte[3][]; //To store 3 attachment
if (item.HasAttachments)
{
EmailMessage message = EmailMessage.Bind(objService, new ItemId(item.Id.UniqueId.ToString()), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
noOfAttachment = message.Attachments.Count;
// Iterate through the attachments collection and load each attachment.
foreach (Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
//Get the Attachment as bytes
if ( i < 3)
{
btAttachments[i] = fileAttachment.Content;
i++;
}
}
// Attachment is an item attachment.
else
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load(new PropertySet(EmailMessageSchema.MimeContent));
MimeContent mc = itemAttachment.Item.MimeContent;
if (i < 3)
{
btAttachments[i] = mc.Content;
i++;
}
}
}
}
Выше кода преобразует все вложения в байты. Когда у вас есть байты, вы можете преобразовать байты в требуемый формат.
Чтобы преобразовать байты в файлы и сохранить их на диске, следуйте приведенным ниже ссылкам:
Запись байтов в файл
http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Save-byte-array-to-file.html
Ответ 7
Вот как я решил проблему для загрузки из EWS сообщения электронной почты в формате .eml через код vbs
' This is the function that retrieves the message:
function CreaMailMsg(ItemId,ChangeKey)
Dim MailMsg
Dim GetItemSOAP,GetItemResponse,Content
LogFile.WriteLine (Now() & "-" & ":CreaMailMsg:ID:" & ItemId)
GetItemSOAP=ReadTemplate("GetItemMsg.xml")
GetItemSOAP=Replace(GetItemSOAP, "<!--ITEMID-->", ItemId)
GetItemSOAP=Replace(GetItemSOAP, "<!--ITEMCHANGEKEY-->", ChangeKey)
LogFile.WriteLine (Now() & ":GetItemSOAP:" & GetItemSOAP)
set GetItemResponse=SendSOAP(GetItemSOAP,TARGETURL,"",USERNAME,PASSWORD)
' Check we got a Success response
if not IsResponseSuccess(GetItemResponse, "m:GetItemResponseMessage","ResponseClass") then
LogFile.WriteLine (Now() & "-" & ":ERRORE:Fallita GetItemMsg:" & GetItemResponse.xml)
Chiusura 1
end if
' LogFile.WriteLine (Now() & "-" & ":DEBUG:riuscita GetItemMsg:" & GetItemResponse.xml)
Content = GetItemResponse.documentElement.getElementsByTagName("t:MimeContent").Item(0).Text
' LogFile.WriteLine (Now() & ":Contenuto MIME" & Content)
CreaMailMsg = WriteAttach2File(Content,"OriginaryMsg.eml")
' MailMsg.close
CreaMailMsg = true
end function
'###########################################################################
' These are the functions the save the message in .eml format
'###########################################################################
function WriteAttach2File(Content,nomeAttach)
Dim oNode,oXML,Base64Decode
' Read the contents Base64 encoded and Write a file
set oXML=CreateObject("MSXML2.DOMDocument")
set oNode=oXML.CreateElement("base64")
oNode.DataType="bin.base64"
oNode.Text = Content
Base64Decode = Stream_Binary2String(oNode.nodeTypedValue,nomeAttach)
Set oNode = Nothing
Set oXML = Nothing
end function
'###########################################################################
function Stream_Binary2String(binary,nomeAttach)
Const adTypeText = 2
Const adTypeBinary = 1
Dim BinaryStream
Set BinaryStream=CreateObject("ADODB.Stream")
BinaryStream.Type=adTypeBinary' Binary
BinaryStream.Open
BinaryStream.Write binary
BinaryStream.Position=0
BinaryStream.Type=adTypeText
BinaryStream.CharSet = "us-ascii"
Stream_Binary2String=BinaryStream.ReadText
'msgbox Stream_Binary2String
BinaryStream.SaveToFile ShareName & "\" & nomeAttach,2
Set BinaryStream=Nothing
end function
Ответ 8
Если вы переходите из Outlook EntryID через VSTO (Hex) в EwsID, вам нужно посмотреть здесь: http://bernhardelbl.wordpress.com/2013/04/15/converting-entryid-to-ewsid-using-exchange-web-services-ews/
Сохранял меня. Я продолжал получать "Данные повреждены". сообщение.