Create an email using EWS Exchange and attach another email - c#

I'm having trouble attaching an email to a new email using EWS.
So i have the Microsoft.Exchnage.Webservice.Data.Item in my findResults.
If I find an issue in the form data of the email then I want to attach that item to a new email and send it to a supervisor for manual input.
I have tried;
EmailMessage newMessage = new EmailMessage(exchange);
newMessage.Subject = "Failed lead creation";
ItemAttachment attachment = new ItemAttachment("New Lead", message);
I can't seem to create the ItemAttachment as the erro I am getting is "ItemAttachment does not contain a constructor that takes 2 arguments".
How do I create a new message in EWS, attach the current Item to it and send to another recipient?
Thaks

You can't another message directly you need to use the MimeContent of the Original Message and then create an ItemAttachment based on that eg something like
FolderId folderid= new FolderId(WellKnownFolderName.Inbox,"MailboxName");
Folder Inbox = Folder.Bind(service,folderid);
ItemView ivItemView = new ItemView(1) ;
FindItemsResults<Item> fiItems = service.FindItems(Inbox.Id,ivItemView);
if(fiItems.Items.Count == 1){
EmailMessage mail = new EmailMessage(service);
EmailMessage OriginalEmail = (EmailMessage)fiItems.Items[0];
PropertySet psPropset= new PropertySet(BasePropertySet.IdOnly);
psPropset.Add(ItemSchema.MimeContent);
psPropset.Add(ItemSchema.Subject);
OriginalEmail.Load(psPropset);
ItemAttachment Attachment = mail.Attachments.AddItemAttachment<EmailMessage>();
Attachment.Item.MimeContent = OriginalEmail.MimeContent;
ExtendedPropertyDefinition PR_Flags = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
Attachment.Item.SetExtendedProperty(PR_Flags,"1");
Attachment.Name = OriginalEmail.Subject;
mail.Subject = "See the Attached Email";
mail.ToRecipients.Add("glen.scales#domain.com");
mail.SendAndSaveCopy();
Cheers
Glen

Utilizing answer from Glen Scales, if you have message id, code should look like below.
Additional info on PR_Flags extended property can be found on folowing link:
http://systemmanager.ru/windowsmobile_6_5.en/html/45cd0e95-9622-4180-bf85-290c421524f3.htm
PropertySet psPropset = new PropertySet(BasePropertySet.IdOnly);
psPropset.Add(ItemSchema.MimeContent);
psPropset.Add(ItemSchema.Subject);
EmailMessage attachment = EmailMessage.Bind(_exchangeService, new ItemId(ewsItemAsAttachment).UniqueId, psPropset).Result;
ItemAttachment Attachment = message.Attachments.AddItemAttachment<EmailMessage>();
Attachment.Item.MimeContent = attachment.MimeContent;
ExtendedPropertyDefinition PR_Flags = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
Attachment.Item.SetExtendedProperty(PR_Flags, "1");
Attachment.Name = attachment.Subject;

Related

EWS Managed API: External GUID in mail message?

Is it possible to assign EmailMessage specific GUID/ID, which will be later used for search?
var email = new EmailMessage(_service);
email.ExternalGuid = /*Guid or Identifier*/;
email.Send();
And later I should be able to use it to find if this mail is present:
var isExist = _service.IsExistByExternalGuid(/*Guid or Identifier*/);
Why don't you use the InternetMessageid eg Internet Message ID FROM EWS Managed API Send Email c# this Id will then appear in any tracking logs associated with the Message and you can search for the message at a later date using a SearchFilter eg
ItemView ivew = new ItemView(3);
service.TraceEnabled = true;
ExtendedPropertyDefinition PidTagInternetMessageId = new ExtendedPropertyDefinition(4149, MapiPropertyType.String);
SearchFilter sf = new SearchFilter.IsEqualTo(PidTagInternetMessageId, MessageID);
FindItemsResults<Item> iCol = service.FindItems(WellKnownFolderName.Inbox, sf, ivew);
foreach (Item item in iCol.Items)
{
Console.WriteLine(item.Subject);
}

Set Deliverynotification and Readnotification for outgoing Mails

I send invoices and warnings/reminders to customers and now these mails should be flagged with a Deliverynotification and Readnotification. So, I know when customers received and read the invoice.
MailMessage email = new MailMessage();
email.Priority = MailPriority.Normal;
email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; // Deliverynotification?
email.Attachments.Add(new Attachment(docDunPath));
email.Attachments.Add(new Attachment(docInvoicePath));
email.Subject = "-----------";
email.IsBodyHtml = true;
email.Body = MailText;
Everything works so far, I just want to set the options for an automatic response when the recipient has read the mail. So, I can be sure he saw his invoice.
So after realising i used System.Net.Mail i switched to Microsoft.Exchange.WebServices and it works perfectly now.
EmailMessage email = new EmailMessage(service);
email.IsDeliveryReceiptRequested = true;
email.IsReadReceiptRequested = true;

Error trying to send mail. Not sending using EWS

I'm connecting fine to the Exchange Server and I'm getting all the unread mails but a new message doesn't want to send
Message Code
var newHTML = html.HTMLCode.Replace("{House}", house.Number)
.Replace("{Token}", token.Number)
.Replace("{contactPerson}",
string.Format("<a href=mailto:{0}>{1}</a>",
contactPerson, contactPerson));
LogError.WriteToFile("Has House and token");
//Send mail with token to user
EmailMessage message = new EmailMessage(emailService);
message.ToRecipients.Add(email.From.Address);
message.Subject = string.Format("Electricity token for: {0}", house.Number);
message.Body = new MessageBody(html.HTMLCode);
LogError.WriteToFile("Trying to send");
message.Send();
I have a try catch around this so in the log file I get "Trying to send" but then a error occurs that reads as
"EmailAddress or ItemId must be included in the request."
From examples seen, the way I construct my message seems sufficient but clearly isn't
This is how I got all my unread emails
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults = emailService.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (EmailMessage email in findResults)
{}
Note that I got them as a "EmailMessage"
But were never able to get the senders email address so that's why it didn't want to send.
and then I found this article: FindItem returns only the first 512 bytes of any streamable property
So then I went to go get that specific email like this. Note that I now get the "Item" from the findResults and with that "Item" I do the following.
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults = emailService.FindItems(WellKnownFolderName.Inbox, sf, view);
foreach (Item item in findResults)
{
//Get the email message
EmailMessage email = EmailMessage.Bind(emailService, item.Id,
new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments));
if (email != null)
{}
}
Now I could finally send emails

Exchange web services - Forward Email as Attachment

I'm currently using Exchange Web Services in C#. I basically have a small application that reads emails from an inbox and process them.
I would like to forward those emails I receive as an attachment of an email. This attachment will be an outlook email that will include the original email (including its own attachments if any).
Any ideas?
Thanks!
EDIT:
Not sure why I'm getting the down votes but it seems this is not possible as the EWS API does not provide such functionality
You can create an ItemAttachment with EWS but you can't replicate fully what is possible in Outlook with MAPI. Eg with EWS you can create an ItemAttachment and then use the MIMEContent to create an attachment based on a current message as a workaround eg
FolderId Inboxid = new FolderId(WellKnownFolderName.Inbox, "target#domain.com");
ItemView InboxItemView = new ItemView(1);
FindItemsResults<Item> inFiResuls = service.FindItems(Inboxid,InboxItemView);
if(inFiResuls.Items.Count == 1){
EmailMessage fwdMail = new EmailMessage(service);
EmailMessage orgMail = (EmailMessage)inFiResuls.Items[0];
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
psPropSet.Add(ItemSchema.MimeContent);
orgMail.Load(psPropSet);
ItemAttachment emAttach = fwdMail.Attachments.AddItemAttachment<EmailMessage>();
emAttach.Item.MimeContent = orgMail.MimeContent;
ExtendedPropertyDefinition pr_flags = new ExtendedPropertyDefinition(3591,MapiPropertyType.Integer);
emAttach.Item.SetExtendedProperty(pr_flags,"1");
emAttach.Name = orgMail.Subject;
fwdMail.Subject = "see Attached";
fwdMail.ToRecipients.Add("user#domain.com");
fwdMail.Send();
}
This however doesn't give full fidelity of all the mapi properties associated with a particular message as the MIMEContent is just that, for most normal email messages this isn't an issue however for a message with an attached Outlook Task or other TNEF attachment then you would loose these of attachments or for other properties like categories,flags you would loose these also (you could copy these manually if needed).
Cheers
Glen
you can forward your email using this way. It first loads and reads the each emails with attachment who has "msg" extension. then forwards it to given address. see the below code
FindItemsResults<Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, newItemView(50,50));
Item[] msgItems = findResults.Where(msgItem => msgItem.HasAttachments).ToArray();
EmailMessage msgInfo = null;
var fileExtensions = new List<string> { "msg", "MSG", "Msg" };
foreach (MSEWS.Item msgItem in msgItems )
{
msgInfo = EmailMessage.Bind(exchange, msgItem.Id);
FileAttachment fa = msgInfo.Attachments[0] asFileAttachment;
if (fileExtensions.Any(ext => ext.Contains(fa.Name.Substring(fa.Name.Length - 3))))
{
fa.Load();
ResponseMessage responseMessage = msgInfo.CreateForward();
responseMessage.BodyPrefix = "messageBody";
responseMessage.ToRecipients.Add("toAddress");
responseMessage.Subject = "subject";
responseMessage.SendAndSaveCopy();
}
}

EWS Managed API: how to set From of email?

I'm using EWS Managed API to sending email. Account "account#domain.com" have permissions "Send as" to use "sender#domain.com" mailbox to send messages (from Outlook, it's work fine).
But I try from code - it's not work, in mail i'm read in the field "From" "account#domain.com".
....
EmailMessage message = new EmailMessage(service);
message.Body = txtMessage;
message.Subject = txtSubject;
message.From = txtFrom;
....
message.SendAndSaveCopy();
How to make sending mail on behalf of another user? :)
It's been a while since I fiddled with the same thing, and I concluded that it isn't possible, in spite of having "Send as" rights.
Impersonation is the only way to go with EWS, see MSDN:
ExchangeService service = new ExchangeService();
service.UseDefaultCredentials = true;
service.AutodiscoverUrl("app#domain.com");
// impersonate user e.g. by specifying an SMTP address:
service.ImpersonatedUserId = new ImpersonatedUserId(
ConnectingIdType.SmtpAddress, "user#domain.com");
If impersonation isn't enabled, you'll have to supply the credentials of the user on behalf of whom you want to act. See this MSDN article.
ExchangeService service = new ExchangeService();
service.Credentials = new NetworkCredential("user", "password", "domain");
service.AutodiscoverUrl("user#domain.com");
Alternatively you can simply specify a reply-to address.
EmailMessage mail = new EmailMessage(service);
mail.ReplyTo.Add("user#email.com");
However, "Send as" rights do apply when sending mail using System.Net.Mail, which in many cases will do just fine when just sending e-mails. There are tons of examples illustrating how to do this.
// create new e-mail
MailMessage mail = new MailMessage();
mail.From = new MailAddress("user#domain.com");
mail.To.Add(new MailAdress("recipient#somewhere.com"));
message.Subject = "Subject of e-mail";
message.Body = "Content of e-mail";
// send through SMTP server as specified in the config file
SmtpClient client = new SmtpClient();
client.Send(mail);
i think you should use the Sender property so the your code should look like:
EmailMessage message = new EmailMessage(service);
message.Body = txtMessage;
message.Subject = txtSubject;
message.Sender= txtFrom;
....
message.SendAndSaveCopy();

Categories

Resources