I am sending Email with the help of SendGrid. Below is the code for that.
var client = new SendGridClient(apiKey);
EmailAddress from = new
EmailAddress("a.b#mycompany.com", "Ashutosh");
List<EmailAddress> tos = new List<EmailAddress>
{
new EmailAddress("a.b#mycompany.com",
"Ashutosh"),
};
StringBuilder emailBodyContent = new StringBuilder();
var textContent = "Hi, ";
emailBodyContent.AppendFormat("<p>Hi, </p>");
emailBodyContent.AppendFormat("<p>This is your email.</p>");
var emailSubject = "Attachment names are not unique";
msg = MailHelper.CreateSingleEmailToMultipleRecipients(from,
tos, emailSubject, textContent, emailBodyContent.ToString());
var response = await client.SendEmailAsync(msg);
Now I want to send Secure Email. I go through the below link
https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/smtp_ports.html
But I have not understood how to set port 587 through code or enable secure email setting for send grid.
If you're using the SendGrid v3 API you need not worry about SMTP at all. You simply call a web API to send e-mail. All calls are HTTPS.
Check out the source code, note the https.
private void InitiateClient(string apiKey, string host, ...)
{
...
var baseAddress = host ?? "https://api.sendgrid.com";
...
I also found below url which says that by default SendGrid uses TLS.
https://sendgrid.com/blog/sendgrid-and-the-future-of-email-security/
Related
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.
How do I send an email with accented letters? Example is pepé#lefrenchplace.com, which should be supported now with RFC 6532
If I send an email to pepé#lefrenchplace.com from gmail's web interface, it is delivered no problem.
I'm using .NET 4.6.1, C#, and SendGrid.
First attempt with SMTP:
var smtp = new SmtpClient(Server)
{
Credentials = new NetworkCredential(Username, ApiKey),
DeliveryFormat = SmtpDeliveryFormat.International
};
var message = new MailMessage(From, To)
{
Subject = Subjet,
Body = BodyPlainText
};
smtp.Send(message);
This throws an SmtpException with the message The client or server is only configured for E-mail addresses with ASCII local-parts: pepé#lefrenchplace.com.
Second attempt API V3 with SendGrid C# library
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_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("pepé#lefrenchplace.com", "Example User");
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);
var response = await client.SendEmailAsync(msg);
I get an Accepted status code returned. On the SendGrid dashboard it shows as Dropped with Invalid as the reason.
Edit August 2020
SendGrid has closed the Github issue. Anybody wanting a standards compliant email provider to send to an internationalized email address should look elsewhere. Mailgun would work
As of right now, SendGrid does not support E-mail addresses with non-ASCII local-parts at all.
They told me it is on their radar but have no time commitment for implementation.
Github issue
I am trying to send an email using amazon's ses service:
String username = "&&&&&&"; // Replace with your SMTP username.
String password = "&&&&&&&"; // Replace with your SMTP password.
String host = "xxxxxxxx";
int port = 25;
String senderAddress = "xxxxxx";
String receiverAddress = inputEmail;
using (var client = new System.Net.Mail.SmtpClient(host, port))
{
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
String message = "Trucking On Demand received a request to reset the password for your account " + inputEmail + ".Your new password is: " + tempPassword;
client.Send
(
senderAddress, // Replace with the sender address.
inputEmail, // Replace with the recipient address.
message,
"This email was delivered through ****."
);
return Ok();
}
}
Why is my request timing out? I have tried searching internet but aws does not have a clear cut answer for this problem except asking me to enable TLS. I believe client.enablessl does that job. Do I need to dispose my client too? i.e. client.dispose();
Judging from official documentation you should connect to port 587.
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.
I have done this before without any issue but now I don't know what's wrong. I have a web page with a button for email which I want to send some data to email addresses with.
I asked our web hosting company for server details and the response I got was:
"You can use the following details for mail.
Incoming mail server: mail.ourSite.com Outgoing mail server: mail.ourSite.com
Username and password are the email address and password associated with the email address.
"
I am not sure about the last line but I created a new email address in the web host's control panel.
The code I use is:
// instantiate a new mail definition and load an html
// template into a string which I replace values in
// then the rest of the code below
md.Subject = String.Format("{0} {1} {2}", emailSubject, firstName, lastName);
MailMessage msg = md.CreateMailMessage(emailAddress, replacements, emailBody, new Control());
md.IsBodyHtml = true;
SmtpClient sc = new SmtpClient(emailServer);
sc.Credentials = new NetworkCredential(emailUsername, emailPassword);
try
{
sc.Send(msg);
}
emailServer - mail.ourSite.com (dummy value in this post)
emailUsername - the email address I created in the control panel
emailPassword - the password for the email above
The error I have is that when I send emails to other domains than our own I get
"Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server."
When I email to an address within our host then it works fine.
The support is not very supportive so I am asking here what you might think the problem could be? I find it strange that I use the password for an email address I created, should it really be like that?
I think that you are using the wrong email address for the NetworkCredential. It should be the one for your email account that you got from the one providing emailServer.
Try this ..
msg.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("Email", "Password");
msg.Credentials = MyCredential;
here is code to send mail..
i hope i will helpful to you..
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}