I want to send text, title of username into an email that I have but how do I add these options so I can call them over to the html file a bit like this here.
MailDefinition oMailDefinition = new MailDefinition();
oMailDefinition.BodyFileName = "~/img/emailskabelon/NewPassword.html";
oMailDefinition.From = Mail;
Dictionary<string, string> oReplacements = new Dictionary<string, string>();
oReplacements.Add("<<name>>", name);
oReplacements.Add("<<password>>", password);
I would therefore like to add some of the values that I would like to have in my html file.
It might be that I should send text, username and other things to the html file and I would like that option.
public async static void Sendmail(string email, string name, string Title, string htmlContent)
{
var api = AzureName;
var client = new SendGridClient(api);
var from = new EmailAddress(Mail, nameFrom);
var to = new EmailAddress(email, name);
var plainTextContent = Regex.Replace(htmlContent, "<[^>]*>", "");
var msg = MailHelper.CreateSingleEmail(from, to, Title, plainTextContent, htmlContent);
var response = client.SendEmailAsync(msg);
await Task.Delay(4255);
}
Related
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.
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");
I am working on sending out order confirmations on a web site with a shop functionality - all pretty much custom designed. I would like an email to be sent out once the order has been placed, ideally with a brief summary/overview of the ordered items.
I have managed to get to the point where the submission of the order triggers an email to be sent to the user, so that is all good. However, my question is how can I customize the email body in a way so it would include the list of ordered items?
Happy to add code from my controller, although I don't really think this is adding much value as this is more of a how-to-question rather than an issue I am encountering.
int orderID = order.ID;
var lineItems = DATADB.LineItemList.Where(x => x.OrderNumber == 0 && x.UserID == userID);
lineItems.ForEach(l => l.OrderNumber = orderID);
DATADB.SaveChanges();
// send order confirmation email
var orderConfirmation = DATADB.LineItemList.Where(x => x.OrderNumber == orderID).ToList();
var ordered = string.Join(",", lineItems);
var msg = new SendGridMessage();
msg.From = new System.Net.Mail.MailAddress("orders#freshNclean.ch", "freshNclean");
msg.AddTo(UserManager.FindById(userID).Email);
msg.Subject = "Deine Bestellung bei freshNclean";
msg.Text = "Hi " + UserManager.FindById(userID).FirstName.ToString() + "! Vielen Dank für Deine Bestellung." + ordered;
// SendGrid credentials
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["SGaccount"], ConfigurationManager.AppSettings["SGpassword"]);
var transportWeb = new Web(credentials);
if (transportWeb != null)
{
transportWeb.DeliverAsync(msg);
}
else
{
Trace.TraceError("Web Transport konnte nicht generiert werden - die Nachricht wurde nicht versandt.");
Task.FromResult(0);
}
Step 1: Get the data in form of objects (if possible in XML format).
Step 2: Create XSLT template to convert this XML format into HTML
Reference: Simplest way to transform XML to HTML with XSLT in C#?
public static string TransformXMLToHTML(string inputXml, string xsltString)
{
XslCompiledTransform transform = new XslCompiledTransform();
using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
transform.Load(reader);
}
StringWriter results = new StringWriter();
using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
transform.Transform(reader, null, results);
}
return results.ToString();
}
STEP 3: Set HTML contents to output of previous method:
var apiKey = some-api-key;
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = GetHTMLFromXML();
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
Hope this helps.
I have a method in my MVC Controller which I am trying to call an API from in order to send an email (The Mail Message is generated in the MVC Method)
Create Mail message is as follows and this works fine.
public static MailMessage CreateMailMessage(string from,
string to,
string cc,
string bcc,
string subject,
string body,
List<Attachment> attachments,
string differentServer,
bool eatError)
{
MailMessage mm = new MailMessage();
mm.From = new MailAddress(from);
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = true;
//send to multiple addresses separated by semi-colon or comma
if (!string.IsNullOrEmpty(to))
{
var toAddresses = to.Split(new char[] { ';', ',' });
foreach (string toAddress in toAddresses)
{
if (!string.IsNullOrWhiteSpace(toAddress))
mm.To.Add(toAddress);
}
}
if (!string.IsNullOrEmpty(cc))
{
mm.CC.Add(cc);
}
if (!string.IsNullOrEmpty(bcc))
{
mm.Bcc.Add(bcc);
}
if (attachments != null)
{
foreach (Attachment attachment in attachments)
{
mm.Attachments.Add(attachment);
}
}
return mm;
}
However in order to send the email I need to write and call a WebAPI method - sending the email is fine - just not sure how to post the mail message and some other properties to a WebAPI Method?
So My WebAPI method at the minute is like:
/// <summary>
/// Method to email the Report
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("api/Document/EmailReport/")]
public HttpResponseMessage EmailFarmFeatures([FromBody]MailMessage email)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
I am attempting to call this WebAPI from MVC Method as below:
private void EmailReport(string reportName, byte[] bytes)
{
ContentType ct = new ContentType(MediaTypeNames.Application.Octet);
var attachments = new List<Attachment>();
var attach = new Attachment(new MemoryStream(bytes), ct);
attach.ContentDisposition.FileName = reportName;
attachments.Add(attach);
string strFrom = ConfigurationManager.AppSettings["FromEmail"];
string strTo = ConfigurationManager.AppSettings["ToEmail"];
string subject = string.Format("Customer Report - {0}", customerId);
string body = string.Format("Report for Customer {0} attached.", customerId);
string mailServer = ConfigurationManager.AppSettings["SmtpServer"];
MailMessage message = EmailHelper.CreateMailMessage(strFrom, strTo, "", "", subject, body, attachments, mailServer, false);
using (var client = new HttpClient())
{
var requestBody = JsonConvert.SerializeObject(message);
var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");
var response = client.PostAsync("http://localhost/myWS/api/Document/EmailReport/", postRequest).GetAwaiter().GetResult();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Error occured emailing report");
}
}
}
I am currently getting an error on this line:
var requestBody = JsonConvert.SerializeObject(message);
[InvalidOperationException: Timeouts are not supported on this stream.]
System.IO.Stream.get_ReadTimeout() +57
GetReadTimeout(Object ) +81
Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +114
[JsonSerializationException: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.]
Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +274
I believe it is something to do with attemptiong to seriliaze the memory stream attachment though I am not sure what the fix is to make sure this attachment gets included on the POST Request to the API Method
MailMessage isn't Serializable Just create a Separate regular object which represents a mail message.
Have a look at this Thread I guess it's pretty much what you need:
(https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5)[https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5]
I am using SendGrid mailhelper (as part of C# SDK) to send email. I need to send to multiple users, and hence I am using Personalization.
I get an error : Bad Request
This is my code:
static async Task Execute(string sub, string body, List<Recipient> recipients)
{
string apiKey = Environment.GetEnvironmentVariable("SendGrid_ApiKey", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
string subject = sub;
Personalization personalization = new Personalization();
SendGrid.Helpers.Mail.Email emails = new SendGrid.Helpers.Mail.Email();
var i = 0;
foreach (var recp in recipients)
{
emails.Address = recp.Email;
emails.Name = recp.FirstName + " " + recp.LastName;
personalization.AddTo(emails);
i++;
}
SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
Content content = new Content("text/plain", body);
Mail mail = new Mail(from, subject, to, content);
mail.AddPersonalization(personalization);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
}
I appreciate if someone could advise me what am I doing incorrect.
Sendgrid API responds with bad request when there are more than 1 email address that is the same in the Personalization object. Make sure all the emails are unique