Exchange Web Services (EWS) API "To" header for alias - exchange-server

I have an inbox set up in exchange, hello#mycompany.com
Additionally, there is an alias for this, news#mycompany.com, so all emails to the news address end up in the hello inbox.
Ideally, I want to be able to tell which alias an email has been sent to, using EWS.
When I send an email to news#mycompany.com, and examine the Internet headers of the message using Microsoft Outlook, the To: header reads To: Hello <news#mycompany.com> which is exactly what I want to see.
However, using EWS, when I look at the ToRecipients property of the message, the reported email address is always that of the primary SMTP address. Also the InternetMessageHeaders property of the Webservices.Data.Item does not contain the To: property. I also can't seem to see the correct address using EWSEditor to examine all the properties of the message.
The answer to this forum post seems to suggest that,
...The Information about the actual email address a message is sent to is stored in the recipients collection which you can't access (outside of exportmessage) in EWS...
How would I go about doing this programatically so I can find the correct To: address?

This works for me:
private static string GetToAddress()
{
ExchangeService exService = new ExchangeService();
exService.Credentials = new NetworkCredential("username", "password", "domain");
exService.Url = new Uri("https://youraddress/EWS/Exchange.asmx");
ExtendedPropertyDefinition PR_TRANSPORT_MESSAGE_HEADERS = new ExtendedPropertyDefinition(0x007D,MapiPropertyType.String);
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties)
{PR_TRANSPORT_MESSAGE_HEADERS, ItemSchema.MimeContent};
FindItemsResults<Item> fiResults = exService.FindItems(WellKnownFolderName.Inbox, new ItemView(1));
foreach (Item itItem in fiResults.Items)
{
itItem.Load(psPropSet);
Object valHeaders;
if (itItem.TryGetProperty(PR_TRANSPORT_MESSAGE_HEADERS, out valHeaders))
{
Regex regex = new Regex(#"To:.*<(.+)>");
Match match = regex.Match(valHeaders.ToString());
if (match.Groups.Count == 2)
return match.Groups[1].Value;
}
return ToAddress;
}
return "Cannot find ToAddress";
}
The code is from:
http://social.technet.microsoft.com/Forums/en-au/exchangesvrdevelopment/thread/1e5bbde0-218e-466e-afcc-cb60bc2ba692

Related

Create mail in Exchange Online inbox programatically

Have been facing an issue since days about EWS. So my scenario is;
I was to programmatically sync GMAIL and EXCHANGE ONLINE. So here is what I have done;
Connect to Gmail using Gmail API
Fetch mail from gmail get the email body, to, from, attachment and
all other thing
connect to Exchange online using EWS 2.0
Now the problem is here, how can I create an email in Inbox which looks like incoming mail from the sender;
Here is the code I have done;
_service = new ExchangeService(ExchangeVersion.Exchange2013);
_service.TraceEnabled = true;
_service.Credentials = new WebCredentials("admin#xyz.onmicrosoft.com", "password");
_service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
_service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "xyz#xyz.onmicrosoft.com");
EmailMessage message = new EmailMessage(_service);
Random r = new Random();
message.Subject = "Email Message";
message.From = new EmailAddress("xyz#gmail.com");
message.Sender = new EmailAddress("xyz#gmail.com");
message.Body = new MessageBody(BodyType.HTML, "<HTML><body><h1>This is a voice mail.</h1></BODY></HTML>");
message.ToRecipients.Add(new EmailAddress(""));
message.Save(WellKnownFolderName.Inbox);
This way its creating an email in inbox but it shows as a draft mail. I dont want it, I want it to look as RECEIVED mail.
Am I doing anything wrong?
You need to set a couple of properties before saving the message.
// Set a delivery time
ExtendedPropertyDefinition PidTagMessageDeliveryTime =
new ExtendedPropertyDefinition(0x0E06, MapiPropertyType.SystemTime);
DateTime deliveryTime = DateTime.Now; // Or whatever deliver time you want
message.SetExtendedProperty(PidTagMessageDeliveryTime, deliveryTime);
// Indicate that this email is not a draft. Otherwise, the email will appear as a
// draft to clients.
ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
message.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1);
These properties aren't settable after the items is saved, so it's important to do it before the first Save call.

Send a mail from outlook by getting To list from SQl server

I am stuck with a issue from 5 days.
I need a way to attain following requirement.
mailing list is present in Database(SQL server)
I have a mail in Outlook
now i have to send mail to all the 200,000 mail ids in Database
**Note one mail can have only 200 mail IDs so
200,000/200=1000 mails **Note: this 200,000 count is not fixed it will decrease and increase>
like jhon#xyz.com will be present today , next day we may need not send to him
his name might be completely removed (so DL is not an option)
I need a way to automate this
All i have a sleep less nights and coffee cups on my desk
I work in ASP.net any PL which meets this need is fine.
I assume that you know how to create sql statement for what you need and how to retrieve data from database in .NET. This means that only issue is actually sending this from outlook.
Here is an article that describes this in detail and piece of code copied from there.
using System;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace OutlookAddIn1
{
class Sample
{
public static void SendEmailFromAccount(Outlook.Application application, string subject, string body, string to, string smtpAddress)
{
// Create a new MailItem and set the To, Subject, and Body properties.
Outlook.MailItem newMail = (Outlook.MailItem)application.CreateItem(Outlook.OlItemType.olMailItem);
newMail.To = to;
newMail.Subject = subject;
newMail.Body = body;
// Retrieve the account that has the specific SMTP address.
Outlook.Account account = GetAccountForEmailAddress(application, smtpAddress);
// Use this account to send the e-mail.
newMail.SendUsingAccount = account;
newMail.Send();
}
public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
{
// Loop over the Accounts collection of the current Outlook session.
Outlook.Accounts accounts = application.Session.Accounts;
foreach (Outlook.Account account in accounts)
{
// When the e-mail address matches, return the account.
if (account.SmtpAddress == smtpAddress)
{
return account;
}
}
throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
}
}
}
What I would suggest is to skip using outlook unless that’s really necessary and send email by directly communicating with SMTP server.
Just search for “how to send email from C#” or something similar and you’ll find a ton of examples.

Reply To Email Address Not Working

I am trying to send an email address in my application as someone (email should show up as if it were sent from that), but anytime I send the email, the name shows up as I supplied, but no matter what I do, the email address is what I am using to authenticate.
Is there any way to have the email to appear as if it is coming from someone I specify or will it always show up as coming from the authenticated email?
Here is what I have...
using (var message = new MailMessage()
{
From = From != new MailAddress(From.Email, From.FormalName),
Subject = Subject,
Body = Body
})
{
if (To != null)
{
foreach (var address in To)
{
message.To.Add(new MailAddress(address.Email, address.FormalName));
}
}
if (CC != null)
{
foreach (var address in CC)
{
message.CC.Add(new MailAddress(address.Email, address.FormalName));
}
}
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myaccount", "mypassword")
};
message.IsBodyHtml = true;
message.Headers.Add("Reply-To", message.From.Address);
smtp.Send(message);
}
It looks like you're expecting the Reply-To: header to indicate who the message is from. In fact, there is a header called From: for this purpose. So try:
message.Headers.Add("From", message.From.Address);
Do note that Gmail will probably add a Sender: header (that may or may not be shown by the recipient's email client) that reflects the actual account you used to send the message.
Best practice when sending automated emails from a specific user is to use the 'on behalf of' syntax (ReplyTo or Sender in MailMessage) in conjunction with a from address from your system see Sending "on behalf of" emails
however you can put the address straight into from as a string so long as your mail server supports it and the receiving mail server does not do a reverse look-up

Forward email using EWS managed api keeping the headers

I am looking for a sample code on how to forward an existing email message (one that is already in my inbox) using the managed api.
When forwarded is there some way to keep a message original headers while forwarding it?
for example someone sent an email to me -i would like that ews will forward it to another recipient without changing the headers (original receive time from ,bcc etc...).
Given an EmailMessage object, you can just call the CreateForwareMessage() method:
var forwareMessage = item.CreateForward();
Regarding the other question: Get the MIME content of the mail and attach it to a new message:
item.Load(new PropertySet(BasePropertySet.IdOnly, ItemSchema.MimeContent));
var mail = new EmailMessage(service);
var attachment = mail.Attachments.AddFileAttachment("Original message.eml", item.MimeContent.Content);
attachment.ContentType = string.Format("message/rfc822; charset={0}", item.MimeContent.CharacterSet);
mail.ToRecipients.Add("hkrause#infinitec.de");
mail.Subject = "testmail";
mail.SendAndSaveCopy();
EDIT:
Create forward message and set reply to header:
var fw = item.CreateForward();
var fwMsg = fw.Save(WellKnownFolderName.Drafts);
fwMsg.ReplyTo.Add("personA#company.com");
fwMsg.SendAndSaveCopy();

Using Redemption to reply to a mail only intermittently sets the body text

I'm using the below method to reply to mails coming in to a business function mailbox.
The body text being added is only intermittently being set. This method is only called when someone has emailed in to unsubscribe from a mailing but the email address of the sender (or in the body) hasn't been found in the database and we want to ask them to send us the mail address they want to unsubscribe.
private void replyToMail(OutlookItem item)
{
RDOSession session = new RDOSession();
session.Logon(null, null, null, true, null, null);
RDOMail thisItem = session.GetMessageFromID(item.EntryID, item.StoreID, null);
RDOMail reply = thisItem.Reply();
RDOAddressEntry optingout = session.AddressBook.GAL.ResolveName("optingout");
//reply.Sender = optingout; this had no effect
reply.SentOnBehalfOf = optingout;
reply.Subject = "Automated Response - Could not complete unsubscribe";
reply.Body = "This is an automated response from the Newsletter unsubscribe system. We couldn't find "+item.Sender+" in our database to unsubscribe you from our mailings.\r\n\r\nPlease reply to this mail and include the email address you want to unsubscribe.\r\n\r\nKind Regards\r\n.";
reply.Send();
session.Logoff();
}
Firstly, if you are already usign OOM, there is no reason to call RDOSession.Logon. You can simply ste the MAPIOBJECT property:
Replace the line session.Logon() with
session.MAPIOBJECT = item.Application.Session.MAPIOBJECT
do not call Logoff.
Secondly, do yo umean the message is received with out a body? Do you see teh empty bofy in the Sent Items folder?
I had to edit thingie.HTMLBody as well as thingie.Body.
I suppose I could have figured out how to tell when to set the value of each one but since I just want to be sure that I have control of the body in this instance I'm simply setting both.

Resources