Madhu Chepuroju
Madhu Chepuroju

Reputation: 11

How to send email with .eml attachment to another email address frpm a shared mailbox with MS Graph API

In one of our project requirement is to read email with fetch attachments from a shared mailbox and send it to another email address. We achieved this functionality via MS Graph API where we are able to send emails with fileattachment only,failing to send itemattchements(.eml).

Please refer below attached piece of code that im trying.When Im triying it is trowing error like the 'item' is missing.

Struggling to send emails with .eml files, any pointer would help

internal static async Task<System.Collections.Generic.IEnumerable> ProcessMessages(string Withattachments, string Withoutattachments, MM_Mailbox MailboxAddress) { string checkMails = ConfigurationManager.AppSettings["mailsNotToKofax"]; var Toptenmessagesquery = graphClient.Users[MailboxAddress.MailBoxSMTPAddress].MailFolders["Inbox"].Messages.Request().Filter("isRead ne true").Top(10).Expand("attachments");

        var task = System.Threading.Tasks.Task.Run(async () => await Toptenmessagesquery.GetAsync());

        var Toptenmessages = task.Result;

        foreach (var message in Toptenmessages)
        {

            int data = 0;
            if (message.HasAttachments == true)
                {
                try
                { foreach (Attachment attachment in message.Attachments)
                        {
                        
                            if (attachment is FileAttachment)
                        {
                            FileAttachment fileAttachment = (FileAttachment) attachment;
                            if (fileAttachment.ContentId != null)
                            {
                                if (fileAttachment.ContentId.ToLower().Contains("pdf"))
                                { data = 1; }
                                if (fileAttachment.ContentId.ToLower().Contains("htm"))
                                { data = 1; }
                                if (fileAttachment.ContentId.ToLower().Contains("tif"))
                                { data = 1; }
                                if (fileAttachment.ContentId.ToLower().Contains("doc"))
                                { data = 1; }
                            }
                        }
                           
                        else if(attachment is ItemAttachment)
                        {
                            if (attachment.ContentType.ToLower().Contains("message"))
                            { data = 1; }
                            if (data == 1)
                            {
                                var task4 = System.Threading.Tasks.Task.Run(async () => await fwdEmailToSaleForce(message, IlistMBForward, smptpadd, MailboxAddress, 0));
                                var sendmessages = task4.Result;
                                await graphClient.Users[MailboxAddress.MailBoxSMTPAddress].Messages[message.Id].Move(Withoutattachments).Request().PostAsync();
                            }
                        }
                            
                        }

internal static async Task fwdEmailToSaleForce(Message message,List<MM_Mailbox_Forward> toAddress, string smptpadd, MM_Mailbox MailboxAddress,int data) {

                var result = toAddress.Where(x => (x.MailBoxSMTPAddress == smptpadd) && (x.Enabled == "1")).FirstOrDefault();
                try
                {                     

                        string from1 = message.From.EmailAddress.Address;
                        string to1 = result.ForwardURL;
                        
                        SendEmail(from1, to1, message.Subject, message.Body, message.Attachments, smptpadd);                                                      

                    }

                }                       
                catch (Exception ex)
                {
                    throw new Exception("Error in send email:",ex);
                }
             return true;
            }
                   

internal static string SendEmail(string fromAddress, string toAddress, string subject, ItemBody body, IMessageAttachmentsCollectionPage attachments, string relayingMailboxAddress) {

        try
        {

            string[] toMail = toAddress.Split(',');
            List<Recipient> toRecipients = new List<Recipient>();
            int i = 0;
            for (i = 0; i < toMail.Count(); i++)
            {
                Recipient toRecipient = new Recipient();
                EmailAddress toEmailAddress = new EmailAddress();

                toEmailAddress.Address = toMail[i];
                toRecipient.EmailAddress = toEmailAddress;
                toRecipients.Add(toRecipient);
            }              

            var mailMessage = new Message
            {
                Subject = string.Concat("|", fromAddress, "|", " ", subject),
                Body = body,
                ToRecipients = toRecipients,
                Attachments = attachments                                       
            };
           
            graphClient
               .Users[relayingMailboxAddress]
               .SendMail(mailMessage, false)
                .Request()
                .PostAsync().Wait();

            return "Email successfully sent.";

        }
        catch (Exception ex)
        {

            throw new Exception("Error in send email:",ex);
        }
    }

Upvotes: 1

Views: 400

Answers (1)

HCU20J47 VISHVA M
HCU20J47 VISHVA M

Reputation: 1

Here are the steps to send an email with an .eml attachment from a shared mailbox using the Microsoft Graph API and C#:

  1. Get an access token for the Microsoft Graph API. You will need the application ID, client secret, and tenant ID for the Azure AD app registration you created.
var clientId = "<clientId>";
var clientSecret = "<clientSecret>"; 
var tenantId = "<tenantId>";

var confidentialClient = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret) 
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClient); 

GraphServiceClient graphClient = new GraphServiceClient(authProvider);
  1. Read the .eml file into a byte array to attach it to the email.
byte[] emlData;
using (var stream = new FileStream("message.eml", FileMode.Open))
{
    emlData = new byte[stream.Length];
    stream.Read(emlData, 0, (int)stream.Length);
}
  1. Construct the email message with the .eml attachment. Specify the shared mailbox in the From property.
var email = new Message
{
    Subject = "Email subject",
    Body = new ItemBody
    {
        Content = "Email body content"
    },
    From = new Recipient
    {
        EmailAddress = new EmailAddress
        {
            Address = "[email protected]"
        }
    },   
    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = "[email protected]"
            }
        }
    },
    Attachments = new List<Attachment>()
    {
        new FileAttachment
        {
            ODataType = "#microsoft.graph.fileAttachment",
            Name = "message.eml",
            ContentType = "message/rfc822",
            ContentBytes = emlData
        }
    }
};
  1. Send the email message
await graphClient.Users["[email protected]"]
    .SendMail(email, true)
    .Request()
    .PostAsync();

This sends the email from the shared mailbox with the .eml attachment using the Microsoft Graph API in C#. The access token allows you to access the shared mailbox, and the eml file is attached as a byte array in the request.

Upvotes: 0

Related Questions