Send Reply with attachment using Microsoft Graph API - c#

I've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.

You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.

Related

C# Exchange EmailMessage Send: As soon as I add an attachement, I get error "No mailbox with such guid"

In my application I use some code to send automated mails over our Exchange server.
My current goal is to send a HTML mail with some pictures as a handout. That pictures shall be attachments of the mail.
To this point the code is working (I have changes internal names in the code example):
ExchangeService MailClient = new ExchangeService
{
UseDefaultCredentials = true,
Url = new Uri("https://<domain.of.company>/EWS/Exchange.asmx")
};
EmailMessage msg = new EmailMessage(MailClient);
msg.ToRecipients.Add(new EmailAddress(user.EmailAddress));
msg.Sender = new EmailAddress("sender#domain.of.company");
msg.Subject = "Some text here";
MessageBody Body = new MessageBody
{
BodyType = BodyType.HTML,
Text = NameOfApplication.Properties.Resources.Embedded_HTML_File
};
msg.Body = Body;
msg.SendAndSaveCopy(new FolderId(WellKnownFolderName.SentItems, "sender#domain.of.company")));
With this code the E-Mail get saved in the "Sent" folder and arrives the target mailbox. Success so far.
But as soon I add an attachement by this (no other changes were made)
msg.Attachments.AddFileAttachment(AppContext.BaseDirectory + "Logo.jpg");
SendAndSaveCopy throws an exception with the description "No mailbox with such guid."
When I comment out the AddFileAttachment line the code is working again.
Any idea whats wrong with attachments?
Found the solution. Reading tooltips might help.
Maybe the day will come, when Microsoft will change SendAndSaveCopy to include this step.
But yes: The error message is misleading.

getting "Unknown Mailbox" error when sending email using EWS API (C#)

I'm simply trying to use the Office 365 API to send an email via the "Send()" function, but am getting back Microsoft.Exchange.Webservices.Data.ServiceResponseException: Mailbox does not exist.
Here's my exchange service:
_emailExchangeService =
new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Url = new Uri(_settings.ExchangeWebServiceEndpoint),
Credentials = new WebCredentials(_settings.AppEmailUserName, _settings.AppEmailPassword),
TraceEnabled = true,
UseDefaultCredentials = false
};
And here's the code I'm using to send the email:
public void SendEmail(MemoryStream attachment, string body, string subject, string recipients, string fromMailbox)
{
EmailMessage message = new EmailMessage(_emailExchangeService);
message.From = fromMailbox;
message.Subject = subject;
message.Body = new MessageBody(BodyType.Text, body);
message.ToRecipients.Add(recipients);
message.Attachments.AddFileAttachment("FileName", attachment);
message.Send();
}
What mailbox am I forgetting to define when sending this, the sent box? I thought the "from" field would define the mailbox for sending items. I'm just not even sure where to do that and my code looks identical to the docs.
Side note: I know the exchange service is set up correctly because if I define an inbox email address and attempt to FindItems(_inbox) on the mailbox, it works.

Mail Sending to multiple users in Dynamics CRM + Plugin

I'm writing plugin C#, to send an email to the users who are under SystemCustomizer role notifying that Contact is creating or Updating.
How to send an email to multiple users (Bulkmailing/ forEach loop for creating mail request to every user)?
Use a query to find each system user entity with the system customiser role.
Then for each user send an email. 1; create the email, 2; send the email.
// Create an e-mail message.
Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = "SDK Sample e-mail",
Description = "SDK Sample for SendEmail Message.",
DirectionCode = true
};
_emailId = _serviceProxy.Create(email);
// Use the SendEmail message to send an e-mail message.
SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};
SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);

Unable to send emails on Azure Web App using Sendgrid

I am unable to send emails on a MVC4 Web App that I configured on Azure. I am being able to send emails locally on my machine, but when I upload the code to my azure app in the cloud, the mail delivery doesn't say it fails, but emails are not delivered, SendGrid doesn't report that the mail was sent on its dashboard either.
Has someone ran into similar issues? Have looked into similar questions with no exact answer.
I did follow the instructions of this article (https://azure.microsoft.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/#reference) without success. Have tried also to the send the emails thru the SendGrid class libraries and by using plain System.Net.Mail.
Any help is appreciated.
Code:
Thanks for the reply. I am using Web.DeliverAsync, this is the code I am using:
// Create network credentials to access your SendGrid account
var username = System.Configuration.ConfigurationManager.AppSettings["smtpUser"];
var pswd = System.Configuration.ConfigurationManager.AppSettings["smtpPass"];
var credentials = new NetworkCredential(username, pswd);
// Create an Web transport for sending email.
SendGrid.Web transportWeb = new SendGrid.Web(credentials);
//var apiKey = System.Configuration.ConfigurationManager.AppSettings["sendgrid_api_key"];
var apiKey = "apikey";
SendGridMessage msg = new SendGridMessage();
msg.Subject = "...";
msg.AddTo(model.Email);
msg.Html = body;
msg.From = new MailAddress("...");
try
{
await transportWeb.DeliverAsync(msg);
}
catch (Exception e)
{
e.ToExceptionless().Submit();
ViewBag.ErrorMsg = e.Message;
return View("Error");
}
Try this:
var apiKey = System.Configuration.ConfigurationManager.AppSettings["sendgrid_api_key"];
// Create an Web transport for sending email.
SendGrid.Web transportWeb = new SendGrid.Web(apiKey);
SendGridMessage msg = new SendGridMessage();
msg.Subject = "...";
msg.AddTo(model.Email);
msg.Html = body;
msg.From = new MailAddress("...");
try
{
await transportWeb.DeliverAsync(msg);
}
catch (Exception e)
{
//e.ToExceptionless().Submit();
ViewBag.ErrorMsg = e.Message;
return View("Error");
}
Also what version of the SendGrid C# library are you using? Make sure it's version 6.3.x or later.

Missing email from "name" when using AWS SES API in C#

When I send an email using AWS SES in a C# application the email names don't show in the received email - only the email addresses show.
The from/to emails I've added are strings in the form " Their Name". It's clearly understanding that as it's sending it to the right place, but just stripping out the names.
internal void SendEmail()
{
try
{
// Construct an object to contain the recipient address.
Destination destination = new Destination();
destination.ToAddresses = toList;
if (ccList.Count > 0) destination.CcAddresses = ccList;
if (bccList.Count > 0) destination.BccAddresses = bccList;
// Create the subject and body of the message.
Body bodyobj = new Body();
if(body!=null) bodyobj.Text = new Content(body);
if(html!=null) bodyobj.Html = new Content(html);
// Create a message with the specified subject and body.
Message message = new Message(new Content(subject), bodyobj);
// Assemble the email.
SendEmailRequest request = new SendEmailRequest();
request.Destination = destination;
request.Message = message;
request.Source = from;
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(Amazon.RegionEndpoint.EUWest1);
SendEmailResponse ser = client.SendEmail(request);
sent=true;
}
catch (Exception e)
{
errmsg = e.Message;
}
}
You can provide recipients with names in the standard email format
Fred Bloggs <fred.bloggs#exmaple.com>
If you specify your ToAddresses as a list of strings of that format, the name will be set properly.
This conforms to the Internet Message Format (rfc5322) spec. See section 3.4.

Categories

Resources