Reputation: 11
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
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#:
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);
byte[] emlData;
using (var stream = new FileStream("message.eml", FileMode.Open))
{
emlData = new byte[stream.Length];
stream.Read(emlData, 0, (int)stream.Length);
}
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
}
}
};
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