Sending email to multiple recipients fails - c#

I am trying to send the same automatic email to multiple email addresses but I can't get it to work.
[HttpGet("largeorderemail")]
public IActionResult LargeOrderEmail()
{
try
{
//var bodyString = $"<h3>{msg}</h3><br/><p> Visit the site <a href='{Startup.appSettings.AllowOrigin}/lidarweb'> LiDAR GIS portal.</a></p>";
var bodyString = $"<h3>email body</h3>" +
<br/>" +
var emailService = new Email { To = "info#tel.net" };
var response = emailService.ExecuteLargeOrder(bodyString);
return Ok();
}
catch (Exception e)
{
Log.Error(e);
return NotFound();
}
}
public async Task<Response> ExecuteLargeOrder(string bodyString)
{
var fromAddr = new EmailAddress(from, "Info");
subject = "large order";
var toAddr = new EmailAddress(to, "User");
plainTextContent = "";
htmlContent = bodyString;
var msg = MailHelper.CreateSingleEmail(fromAddr, toAddr, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
return response;
}
When I send an email to a single address, it works. Like so: var emailService = new Email { To = "info#tel.net" };
but when I try something like this, it doesn't send the email var emailService = new Email { To = "info#tel.net, info#gmail.com" };
I also tried separating the address like so var emailService = new Email { To = "info#tel.net; info#gmail.com" }; but this also doesn't work.
Any suggestions?

Instead of putting Email addresses, try doing this way. Keep all your Email address in Array and try looping through the Array so that you can achieve your goal.

Related

How to send existing email from shared mailbox to other email address using graph API c#

How to send existing email from inbox to other email address using graph API c#
I have tried sending the existing email but Im not able to send it.
It is throwing error -Code: generalException Message: Unexpected exception returned from the service.
Below is the code snippet:
internal static async Task<System.Collections.Generic.IEnumerable<Message>> Sendemail(List<MM_Mailbox_Forward> toAddress, string smptpadd)
{
string from ="xyz#gmail.com"``your text``
var Toptenmessages1 = graphClient.Users["xyz#gmail.com"].MailFolders["Inbox"].Messages.Request().Top(1);
var task = System.Threading.Tasks.Task.Run(async () => await Toptenmessages1.GetAsync());
var authResult2 = task.Result;
foreach (var message in authResult2)
{
try
{
var messages = new Message
{
Subject = message.Subject,
Body = message.Body,
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc#gmail.com"
}
}
},
};
await graphClient
.Users[from]
.SendMail(messages, true)
.Request()
.PostAsync();
}
}
catch (Exception ex)
{
Console.WriteLine("error:" + ex);
}
Make sure you are not using a shared email box, you can't (by default) send email with a shared email box.

Amazon SES error: The From ARN is not a valid SES identity

I am new to amazone SES and trying to set up my .net core API to send emails using SES. Here is code I`m using to send emails:
SendEmailRequest request = new SendEmailRequest();
request.FromEmailAddress = "email#outlook.com";//verified
//request.
Destination destination= new Destination();
destination.ToAddresses = new List<string> {"some verified email"};
request.Destination = destination;
EmailContent content = new EmailContent();
content.Simple = new Message
{
Body = new Body
{
Html = new Content
{
Data = $#"<html>
//here is some code
</html>"
}
},
Subject = new Content{
Data = "some subject"
}
};
request.Content = content;
request.FromEmailAddressIdentityArn = senderArn;
var status = await _sesClient.SendEmailAsync(request);
This code gives me such error: The From ARN <arn:aws:ses:eu-central-1:xxxxxxxxxxxxxx> is not a valid SES identity.
On AWS console emails are verified:
Any ideas what I`m doing wrong?
Here is .NET Code that does work. The sender has to be verified in SES. See https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html.
public async void SendMessage(string text, string toAddress)
{
var sesClient = new AmazonSimpleEmailServiceClient(RegionEndpoint.USWest2);
var sender = "scmacdon#amazon.com";
var emailList = new List<string>();
emailList.Add(toAddress);
var destination = new Destination
{
ToAddresses = emailList
};
var content = new Content
{
Data = text
};
var sub = new Content
{
Data = "Amazon Rekognition Report"
};
var body = new Body
{
Text = content
};
var message = new Message
{
Subject = sub,
Body = body
};
var request = new SendEmailRequest
{
Message = message,
Destination = destination,
Source = sender
};
try
{
await sesClient.SendEmailAsync(request);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Update
Make sure you are using this version.

trying to accept photo as Microsoft chat bot attachment and send it as an email attachment C#

i am trying to accept a photo as an attachment in Microsoft chat-bot waterFall Dialog...then sending it as an attachment or (even in the body) of an email functionality (which i created)..
the email functionality seems to be working....however i am unable to pass the photo attachment in the email
it is like:
cannot convert from microsoft bot schema attachment to string
this is my code : the first method is to ask user to upload photo
private static async Task<DialogTurnResult> UploadAttachmentAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
stepContext.Values["desc"] = (string)stepContext.Result;
if (lang == "en")
{
lang = "en";
return await stepContext.PromptAsync(
attachmentPromptId,
new PromptOptions
{
Prompt = MessageFactory.Text($"Can you upload a ScreenShot of the Error?"),
});
}
else if (lang == "ar")
{
lang = "ar";
return await stepContext.PromptAsync(
attachmentPromptId,
new PromptOptions
{
Prompt = MessageFactory.Text($"هل يمكنك تحميل لقطة شاشة للخطأ؟"),
});
}
else return await stepContext.NextAsync();
}
the second method is the upload code itself:
private async Task<DialogTurnResult> UploadCodeAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
List<Attachment> attachments = (List<Attachment>)stepContext.Result;
string replyText = string.Empty;
foreach (var file in attachments)
{
// Determine where the file is hosted.
var remoteFileUrl = file.ContentUrl;
// Save the attachment to the system temp directory.
var localFileName = Path.Combine(Path.GetTempPath(), file.Name);
// Download the actual attachment
using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}
replyText += $"Attachment \"{file.Name}\"" +
$" has been received and saved to \"{localFileName}\"\r\n";
}
return await stepContext.NextAsync();
}
and the third is to store the photo as activity result to pass it later
private static async Task<DialogTurnResult> ProcessImageStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
stepContext.Values["picture"] = ((IList<Attachment>)stepContext.Result)?.FirstOrDefault();
await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = MessageFactory.Text("Attachment Recieved...Thank you!!") }, cancellationToken);
return await stepContext.EndDialogAsync();
}
and finally the step where i am storing the values i got from each stepcontext and should be passed in an email body: (the attachment is supposed to be stoted in ticketProfile.screenShot)
private static async Task<DialogTurnResult> SummaryStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var ticketProfile = await _ticketDialogAccessor.GetAsync(stepContext.Context, () => new Ticket(), cancellationToken);
ticketProfile.userType = (string)stepContext.Values["userType"];
ticketProfile.staffType = (string)stepContext.Values["staffType"];
ticketProfile.empIdInfo = (string)stepContext.Values["shareId"];
ticketProfile.emailInfo = (string)stepContext.Values["shareEmail"];
ticketProfile.helpType = (string)stepContext.Values["helpType"];
ticketProfile.describeHelp = (string)stepContext.Values["desc"];
ticketProfile.screenShot = (Attachment)stepContext.Values["picture"];
string[] paths = { ".", "adaptiveCard.json" };
var cardJsonObject = JObject.Parse(File.ReadAllText(Path.Combine(paths)));
var userEmailValue = cardJsonObject.SelectToken("body[2].facts[0]");
var userIdValue = cardJsonObject.SelectToken("body[2].facts[1]");
var userTypeValue = cardJsonObject.SelectToken("body[2].facts[2]");
var staffTypeValue = cardJsonObject.SelectToken("body[2].facts[3]");
var helpTypeValue = cardJsonObject.SelectToken("body[2].facts[4]");
var describeValue = cardJsonObject.SelectToken("body[2].facts[5]");
userEmailValue["value"] = ticketProfile.emailInfo;
userIdValue["value"] = ticketProfile.empIdInfo;
userTypeValue["value"] = ticketProfile.userType;
staffTypeValue["value"] = ticketProfile.staffType;
helpTypeValue["value"] = ticketProfile.helpType;
describeValue["value"] = ticketProfile.describeHelp;
var attachment = new Attachment()
{
Content = cardJsonObject,
ContentType = "application/vnd.microsoft.card.adaptive"
};
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(attachment);
await stepContext.Context.SendActivityAsync(reply);
Email($"Here you go{Environment.NewLine}{ticketProfile.screenShot}");
return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}
the email function:
public static void Email(string htmlString)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.From = new MailAddress("hassanjarko55#gmail.com");
mail.Subject = "New Ticket";
mail.Body = htmlString;
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential("user Name, "password");
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
mail.To.Add(new MailAddress("hassan.jarko#yahoo.com"));
mail.IsBodyHtml = true;
SmtpServer.Send(mail);
}
catch (Exception e)
{
e.ToString();
}
}
public class Ticket
{
public string userType { get; set; }
public string staffType { get; set; }
public string helpType { get; set; }
public string helpWith { get; set; }
public string describeHelp { get; set; }
public Attachment screenShot { get; set; }
public string emailInfo { get; set; }
public string empIdInfo { get; set; }
}
any help will be much appreciated...thanks in advance
thanks a lot for #Alphonso...appreciate your efforts to hep...
i did the following to send the picture received from my chatbot as attachment as an email:
1-moved my email functionality method inside SummaryStepAsync method.
2-downloaded the image accepted from user using WebClient
string contentURL = ticketProfile.screenShot.ContentUrl;
string name = ticketProfile.screenShot.Name;
using (var client = new WebClient())
{
client.DownloadFile(contentURL, name);
client.DownloadData(contentURL);
client.DownloadString(contentURL);
}
3-passed it to my email functionality
try
{
HttpClient httpClient = new HttpClient();
//Help Desk Email Settings
MailMessage helpDeskMail = new MailMessage();
if (ticketProfile.screenShot != null)
{
System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(ticketProfile.screenShot.Name);
helpDeskMail.Attachments.Add(data);
}
that's it :)
Have you tried attaching the file name instead of attaching a microsoft.bot.schema.attachment type
also have a look # this it might help you
How do I add an attachment to an email using System.Net.Mail?
Also also in you email function you need to add this code in order to have an attachment in your email
mail.Attachments.Add(new Attachment());
Note: I don't have that big knowledge in C# but I like to participate in these type of questions that have no answers to help the future programmers

SendGrid Add Category to mail

I am using SendGrid, and I want to add one or more category to the email, but the added category hadn't been sent!
This is the code:
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
//FYI, the following three variables are not real
var apiKey = "SG.XXX";
var fromEmail = "";
var toEmail = "";
var client = new SendGridClient(apiKey);
var from = new EmailAddress(fromEmail);
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress(toEmail);
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
msg.AddHeader("category", "cat1"); //This line does nothing!
var response = await client.SendEmailAsync(msg);
}
}
Thanks Kami, I tried your answer and it worked properly.
I replaced this line msg.AddHeader("category", "cat1"); with msg.AddCategory("cat1");

Sending Email Using SendGrid

I'm trying to send email from sendgrid as follows-
public static async Task<int> SendEmail(string fromEmail, string toEmail, string emailMessage, string subject)
{
try
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
// Add the message properties.
myMessage.AddTo(toEmail);
myMessage.From = new MailAddress(fromEmail);
myMessage.Subject = subject;
myMessage.Html = emailMessage;
var username = ConfigurationManager.AppSettings["NetworkUserId"];
var pswd = ConfigurationManager.AppSettings["NetworkUserPwd"];
var domain = ConfigurationManager.AppSettings["HostName"];
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(username, pswd, domain);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
if (transportWeb != null)
await transportWeb.DeliverAsync(myMessage);
else
{
await Task.FromResult(0);
}
}
catch (System.Exception ex)
{
//throw ex;
}
return 1;
}
Here I'm using async and await, I got mail successfully but I'm expecting return value as 1. I think my debugger hitch into await.
You do not need to await the result of 0, your code should be:
public static async Task<int> SendEmail(string fromEmail, string toEmail, string emailMessage, string subject) {
try {
// Same as your example
if (transportWeb != null)
await transportWeb.DeliverAsync("");
else {
return 0;
}
}
catch (System.Exception ex) {
//throw ex;
}
return 1;
}

Categories

Resources