Exchange Web Services - Send email with attachment
Asked Answered
T

3

10

I'm new to using EWS (Exchange Web Service) and I'm looking for a simple example that demonstrates how to send an email with an attachment. I've searched for an example and I can't find any that are simple and clear-cut. I've found examples about how to send an email but not sending an email with an attachment.

Does anyone have a link to an example they would recommend? Posting an example here would work just as well!

Tadzhik answered 29/9, 2010 at 15:42 Comment(2)
Are you using the Managed API or just EWS? The bits vary slightly but are still pretty easy. Follow the tutorial you've found to create an email instance and then in the Managed API all you need to do is: email.Attachments.Add(fileName);Donnelly
I'm using just EWS. I found one example that creates a FileAttachmentType and then creates a CreateAttachmentType from that file attachment. It then calls ews.CreateAttachment using the CreateAttachmentType. Is that what I should be doing? I was hoping it would be a bit more intuitive, as your answer suggests, but I'm finding that attaching a file to an email is a bit more "fuzzy" than I expected.Tadzhik
T
9

Well, I eventually figured this out. Here is a method that will create a mail message, store it as a draft, add the attachment and then send the email. Hope this helps someone out there who wasn't able to find a good example like me.

In my example, I'll only be sending excel files which is why the content type is set like it is. This can, obviously, be changed to support any type of file attachment.

For your reference, the variable esb is a class level variable of type ExchangeServiceBinding.

Edit

I should also note that in this example, I'm not checking the response types from the exchange actions for success or failure. This should definitely be checked if you care to know whether or not your calls to EWS actually worked.

public void SendEmail(string from, string to, string subject, string body, byte[] attachmentAsBytes, string attachmentName)
        {
            //Create an email message and initialize it with the from address, to address, subject and the body of the email.
            MessageType email = new MessageType();

            email.ToRecipients = new EmailAddressType[1];
            email.ToRecipients[0] = new EmailAddressType();
            email.ToRecipients[0].EmailAddress = to;

            email.From = new SingleRecipientType();
            email.From.Item = new EmailAddressType();
            email.From.Item.EmailAddress = from;

            email.Subject = subject;

            email.Body = new BodyType();
            email.Body.BodyType1 = BodyTypeType.Text;
            email.Body.Value = body;

            //Save the created email to the drafts folder so that we can attach a file to it.
            CreateItemType emailToSave = new CreateItemType();
            emailToSave.Items = new NonEmptyArrayOfAllItemsType();
            emailToSave.Items.Items = new ItemType[1];
            emailToSave.Items.Items[0] = email;
            emailToSave.MessageDisposition = MessageDispositionType.SaveOnly;
            emailToSave.MessageDispositionSpecified = true;

            CreateItemResponseType response = esb.CreateItem(emailToSave);
            ResponseMessageType[] rmta = response.ResponseMessages.Items;
            ItemInfoResponseMessageType emailResponseMessage = (ItemInfoResponseMessageType)rmta[0];

            //Create the file attachment.
            FileAttachmentType fileAttachment = new FileAttachmentType();
            fileAttachment.Content = attachmentAsBytes;
            fileAttachment.Name = attachmentName;
            fileAttachment.ContentType = "application/ms-excel";

            CreateAttachmentType attachmentRequest = new CreateAttachmentType();
            attachmentRequest.Attachments = new AttachmentType[1];
            attachmentRequest.Attachments[0] = fileAttachment;
            attachmentRequest.ParentItemId = emailResponseMessage.Items.Items[0].ItemId;

            //Attach the file to the message.
            CreateAttachmentResponseType attachmentResponse = (CreateAttachmentResponseType)esb.CreateAttachment(attachmentRequest);
            AttachmentInfoResponseMessageType attachmentResponseMessage = (AttachmentInfoResponseMessageType)attachmentResponse.ResponseMessages.Items[0];

            //Create a new item id type using the change key and item id of the email message so that we know what email to send.
            ItemIdType attachmentItemId = new ItemIdType();
            attachmentItemId.ChangeKey = attachmentResponseMessage.Attachments[0].AttachmentId.RootItemChangeKey;
            attachmentItemId.Id = attachmentResponseMessage.Attachments[0].AttachmentId.RootItemId;

            //Send the email.
            SendItemType si = new SendItemType();
            si.ItemIds = new BaseItemIdType[1];
            si.SavedItemFolderId = new TargetFolderIdType();
            si.ItemIds[0] = attachmentItemId;
            DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
            siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
            si.SavedItemFolderId.Item = siSentItemsFolder;
            si.SaveItemToFolder = true;

            SendItemResponseType siSendItemResponse = esb.SendItem(si);
        }
Tadzhik answered 4/10, 2010 at 19:44 Comment(0)
I
4

I know this question is very old, but I landed here after searching google. Here is an updated simplified working answer with using statements.

You need to add the nuget package Microsoft.Exchange.WebServices to your project (current version is 2.2.0).

using Microsoft.Exchange.WebServices.Data;

namespace Exchange
{
    public static class Emailer
    {
        public static void SendEmail(string from, string to, string subject, string body, byte[] attachmentBytes, string attachmentName)
        {
            var service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            service.AutodiscoverUrl(from);
            var message = new EmailMessage(service)
            {
                Subject = subject,
                Body = body,
            };
            message.ToRecipients.Add(to);
            message.Attachments.AddFileAttachment(attachmentName, attachmentBytes);
            message.SendAndSaveCopy();
        }
    }
}

The call to service.AutodiscoverUrl can take many seconds - if you know the url then you can avoid calling AutodiscoverUrl and set it directly. (You can recover it once by calling AutodiscoverUrl then printing service.Url.)

// service.AutodiscoverUrl(from); // This can be slow
service.Url = new System.Uri("https://outlook.domain.com/ews/exchange.asmx");
Inappropriate answered 17/10, 2016 at 14:20 Comment(1)
I experienced one system that used the save to draft approach mentioned in another post, and there was an issue where the delivery email address was getting altered by exchange and mails were subsequently not getting sent, so I would now use @Inappropriate approach not only for its much greater simplicity, but also as something as less prone to error. Great tip on the AutoDiscoverUrl method too. Many thanks.Sliwa
P
0

I faced with same issue, when tried to send email with file attachment via EWS using SOAP webservices. Finally solution was found.

1)Create message and get ID of it.

    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">

  <soap:Body>
    <CreateItem MessageDisposition="SaveOnly"
    xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">

      <SavedItemFolderId>
        <t:DistinguishedFolderId Id="drafts" />
      </SavedItemFolderId>
      <Items>
        <t:Message>
          <t:ItemClass>IPM.Note</t:ItemClass>
          <t:Subject>test 2</t:Subject>
          <t:Body BodyType="HTML">this is
          &lt;b&gt;bold&lt;/b&gt;</t:Body>
          <t:ToRecipients>
            <t:Mailbox>
              <t:EmailAddress>[email protected]</t:EmailAddress>
            </t:Mailbox>
          </t:ToRecipients>
          <t:IsRead>false</t:IsRead>
        </t:Message>
      </Items>
    </CreateItem>
  </soap:Body>
</soap:Envelope>

Get Response:

    <?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1497" MinorBuildNumber="46" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:CreateItemResponseMessage ResponseClass="Success">
                    <m:ResponseCode>NoError</m:ResponseCode>
                    <m:Items>
                        <t:Message>
                            <t:ItemId Id="AAAYAE5pa29sYXkuR3VyeWFub3ZAYXphbC5hegBGAAAAAAAM4X07f1m5TruMA1KYuHzKBwCYiVmSeaoqQ5DPKXS6XYPUAAAAv1MsAACiYL/sCHf3TKGIeSfzqioDAAbhmG/mAAA=" ChangeKey="CQAAABYAAACiYL/sCHf3TKGIeSfzqioDAAbiJMe3"/>
                        </t:Message>
                    </m:Items>
                </m:CreateItemResponseMessage>
            </m:ResponseMessages>
        </m:CreateItemResponse>
    </s:Body>
</s:Envelope>

2)Create file attachment. Before do that turn your file into binary code and encrypt it with Base64 method. Then put hash of file to the tag "Content" like in below example:

    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">

  <soap:Body>
    <CreateAttachment xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"
    xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">

      <ParentItemId Id="AAAYAE5pa29sYXkuR3VyeWFub3ZAYXphbC5hegBGAAAAAAAM4X07f1m5TruMA1KYuHzKBwCYiVmSeaoqQ5DPKXS6XYPUAAAAv1MsAACiYL/sCHf3TKGIeSfzqioDAAbhmG/mAAA=" />
      <Attachments>
        <t:FileAttachment>
          <t:Name>kassa.ini</t:Name>
          <t:Content>
          W0dlbmVyYWxdDQpzaG9wbm89OTkNCg0KDQpkYXRhc2hvcD1jOlxkcmVhbVxkYXRhc2hvcCAyLjAuYWNjZGINCmRhdGFISz1jOlxkcmVhbVxkYXRhSEsubWRiDQoNCnJlbSB2b29ycmFhZCB3YWFyc2NodXdpbmcNCnZvb3JyYWFkd2FhcnNjaHV3aW5nPS0xDQoNCnJlbSBwaW5uZW4NCkhlZWZ0UE9JUD0wDQpYVElMTkVYVD0tMQ0KDQpyZW0gbW9uc3RlciBrYXNzYQ0KSXNtb25zdGVyPTANCg0KcmVtIGF1dG9pbnZvZXIga25vcA0KYXV0b2ludm9lcj0tMQ0KDQpyZW0gdG91Y2hzY3JlZW4NCnRvdWNoc2NyZWVuPTANCg0KDQpbcGluXQ0KZGVmYXVsdHBpbj0wNQ0KcGluMDU9UkVOVDAxDQpwaW4wMz1HU00wMQ0KDQpbZXJyb3JdDQo=</t:Content>
        </t:FileAttachment>
      </Attachments>
    </CreateAttachment>
  </soap:Body>
</soap:Envelope>

Get the response:

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1497" MinorBuildNumber="46" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <m:CreateAttachmentResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:CreateAttachmentResponseMessage ResponseClass="Success">
                    <m:ResponseCode>NoError</m:ResponseCode>
                    <m:Attachments>
                        <t:FileAttachment>
                            <t:AttachmentId Id="AAAYAE5pa29sYXkuR3VyeWFub3ZAYXphbC5hegBGAAAAAAAM4X07f1m5TruMA1KYuHzKBwCYiVmSeaoqQ5DPKXS6XYPUAAAAv1MsAACiYL/sCHf3TKGIeSfzqioDAAbhmG/mAAABEgAQAPuV+vqkAj1FltQh+hc7myw=" RootItemId="AAAYAE5pa29sYXkuR3VyeWFub3ZAYXphbC5hegBGAAAAAAAM4X07f1m5TruMA1KYuHzKBwCYiVmSeaoqQ5DPKXS6XYPUAAAAv1MsAACiYL/sCHf3TKGIeSfzqioDAAbhmG/mAAA=" RootItemChangeKey="CQAAABYAAACiYL/sCHf3TKGIeSfzqioDAAbiJMe5"/>
                        </t:FileAttachment>
                    </m:Attachments>
                </m:CreateAttachmentResponseMessage>
            </m:ResponseMessages>
        </m:CreateAttachmentResponse>
    </s:Body>
</s:Envelope>

3)Now you can send email using the below request. Make sure you put correct ID and "Change key" value to the request. These values you get when receive response from above request.

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">

  <soap:Body>
    <SendItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"
    SaveItemToFolder="true">
      <ItemIds>
        <t:ItemId Id="AAAYAE5pa29sYXkuR3VyeWFub3ZAYXphbC5hegBGAAAAAAAM4X07f1m5TruMA1KYuHzKBwCYiVmSeaoqQ5DPKXS6XYPUAAAAv1MsAACiYL/sCHf3TKGIeSfzqioDAAbhmG/mAAA="
        ChangeKey="CQAAABYAAACiYL/sCHf3TKGIeSfzqioDAAbiJMe5" />
      </ItemIds>
    </SendItem>
  </soap:Body>
</soap:Envelope>

response:

 <?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1497" MinorBuildNumber="46" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <m:SendItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
            <m:ResponseMessages>
                <m:SendItemResponseMessage ResponseClass="Success">
                    <m:ResponseCode>NoError</m:ResponseCode>
                </m:SendItemResponseMessage>
            </m:ResponseMessages>
        </m:SendItemResponse>
    </s:Body>
</s:Envelope>

Now all done. Email with file attachment sent successfully.

Previdi answered 23/10, 2023 at 6:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.