Microsoft recently released the Exchange Web Services Managed API SDK 1.0. This mouthful which I’ll just call EWSMAS is useful for writing custom applications that work with Exchange Server (2007 SP1 or 2010). In one of the projects we are currently working on, we need to send emails over Exchange with both normal attachments as well as inline in the mail body.
Now here’s the good thing – if you’re already on Exchange 2010, there is a simple property called IsInline that will allow you to specify the attachment as inline. However, if you’re on Exchange 2007 SP1 still (like in the case of Exchange Online/BPOS), you’re stuck as the property returns an exception stating it’s only for Exchange 2010. Here’s how to solve this problem. Note that I’ve created a simple console app to demonstrate this method only. I assume you know how to download the SDK and add reference to it in VS2008/2010.
1: ExchangeService service =
2: new ExchangeService(ExchangeVersion.Exchange2007_SP1);
3:
4: // Use when machine is IN Domain
5: //service.UseDefaultCredentials = true;
6: //service.AutodiscoverUrl("user@domain.com");
7:
8: // Use when machine is NOT in Domain
9: service.Credentials = new WebCredentials("user@domain.com", "password");
10: service.Url = new Uri("https://Your-CAS-Server/EWS/Exchange.asmx");
11:
12: // Create an e-mail message and identify the Exchange service.
13: EmailMessage message = new EmailMessage(service);
14:
15: // Add properties to the e-mail message.
16: message.Subject = "Testing from .NET Client";
17:
18: // Add the image as inline attachment
19: FileAttachment attachment =
20: message.Attachments.AddFileAttachment("C:\\temp\\attach.png");
21: attachment.ContentId = "01"; // this should be unique - say a GUID
22:
23: // Add the message body which refers to this contentID
24: message.Body = "Sent from a .NET with inline image <img src='cid:01'>";
25: message.Body.BodyType = BodyType.HTML;
26:
27: // Add recipeint
28: message.ToRecipients.Add("anotheruser@domain.com");
29:
30: // Send the e-mail message and save a copy.
31: message.SendAndSaveCopy();
Notes:
- Lines 5-6 should be used when the machine sending the mail is in the same AD domain as the Exchange server (say, an in-house Exchange server)
- Lines 9-10 should be used when the machine sending the mail is in a different AD domain from the Exchange server (say, hosted Exchange or BPOS)
- Line 21 is the one that sets a ContentId property for the image attachment – this will now NOT show the image as an attachment anymore. In case you need to simply add it again – this time without the ContentId.
- Line 24 uses this ContentId with the cid: property in a standard HTML image tag. This is what makes the image show up inline in the right place.
This is what the inline image looks like once it is sent and received.
Tags:
ews,
exchange,
.net
Categories:
Development |
Microsoft |
Exchange