Sending html template via amazon ses - c#

I'm using the below code to send plan text but it's not working in html template..
static void Main(string[] args)
{
String username = "test"; // Replace with your SMTP username.
String password = "test"; // Replace with your SMTP password.
String host = "email-smtp.us-east-1.amazonaws.com";
int port = 25;
using (var client = new System.Net.Mail.SmtpClient(host, port))
{
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send
(
"sales#imagedb.com", // Replace with the sender address.
"rohit#imagedb.com", // Replace with the recipient address.
"Testing Amazon SES through SMTP",
"This email was delivered through Amazon SES via the SMTP end point."
);
}

You need to use AlternateViews with the .NET SmtpClient to send HTML messages. The mail client will render the appropriate views that it can support.
Here is a code snippet that demonstrates how to create a message with a text view and an HTML view, and then send the message via Amazon SES.
string host = "email-smtp.us-east-1.amazonaws.com";
int port = 25;
var credentials = new NetworkCredential("ses-smtp-username", "ses-smtp-password");
var sender = new MailAddress("sender#example.com", "Message Sender");
var recipientTo = new MailAddress("recipient+one#example.com", "Recipient One");
var subject = "HTML and TXT views";
var htmlView = AlternateView.CreateAlternateViewFromString("<p>This message is <code>formatted</code> with <strong>HTML</strong>.</p>", Encoding.UTF8, MediaTypeNames.Text.Html);
var txtView = AlternateView.CreateAlternateViewFromString("This is a plain text message.", Encoding.UTF8, MediaTypeNames.Text.Plain);
var message = new MailMessage();
message.Subject = subject;
message.From = sender;
message.To.Add(recipientTo);
message.AlternateViews.Add(txtView);
message.AlternateViews.Add(htmlView);
using (var client = new SmtpClient(host, port))
{
client.Credentials = credentials;
client.EnableSsl = true;
client.Send(message);
}

Related

How do I to use MailMessage to send mail using SendGrid?

I'm trying to send mail using SendGrid but I can't. It always throws an exception that I can't fix.
How do I to fix this issue ?
SendMail
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName){
try{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo) {
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = CustomEmail.SENDGRID_SMTP_SERVER;
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail);
return true;
}catch (SmtpException e){
Debug.WriteLine(e.Message);
return false;
}
}
CustomMail
//SendGrid Configs
public const String SENDGRID_SMTP_SERVER = "smtp.sendgrid.net";
public const int SENDGRID_PORT_587 = 587;
public const String SENDGRID_API_KEY_USERNAME = "apikey"; //myself
public const String SENDGRID_API_KEY_PASSWORD = "SG.xx-xxxxxxxxxxxxxxxxxxxxxxxxx-E";
Exception
Exception thrown: 'System.Net.Mail.SmtpException' in System.dll
Server Answer: Unauthenticated senders not allowed
For sending emails with SendGrid there is v3 API. The NuGet name is SendGrid and the link is here.
This library does not work with System.Net.Mail.MailMessage, it uses SendGrid.Helpers.Mail.SendGridMessage.
This library uses an API key for authorization. You can create one when you log into SendGrid web app, and navigate to Email API -> Integration Guide -> Web API -> C#.
var client = new SendGridClient(apiKey);
var msg = MailHelper.CreateSingleTemplateEmail(from, new EmailAddress(to), templateId, dynamicTemplateData);
try
{
var response = client.SendEmailAsync(msg).Result;
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.Accepted)
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
}
}
catch (WebException exc)
{
throw new WebException(new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(), exc);
}
I think your problem stems from not instantiating the SMTP client with the server in the constructor. Also you should wrap your smtpclient in a using statement so it disposes of it properly, or call dispose once you're finished.
Try this:
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName)
{
try
{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo)
{
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
using(SmtpClient smtp = new SmtpClient(CustomEmail.SENDGRID_SMTP_SERVER)){
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail)
}
}
catch (SmtpException e)
{
Debug.WriteLine(e.Message);
return false;
}
}
If that doesn't work you could try removing the port, enablessl and usedefaultcredentials parameters for the smtp client. I use sendgrid all the time and don't use those options.
To more specifically answer your original question and the cause of your exception, the SendGrid SMTP server probably isn't looking for your account's username and password, but rather your API key. The error seems to indicate your authentication is not successful.
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
To integrate with SendGrids SMTP API:
Create an API Key with at least "Mail" permissions.
Set the server host in your email client or application to smtp.sendgrid.net.
This setting is sometimes referred to as the external SMTP server or the SMTP relay.
Set your username to apikey.
Set your password to the API key generated in step 1.
Set the port to 587.
Using the SendGrid C# library will also simplify this process:
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
// using SendGrid's C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
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("test#example.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);
}
}
}

How to add a string to a HTML file while sending it as email in asp .net

I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?
This is the code which I used to send the html file via Email. So how can I add a string(authenticationCode) to HTML file to send it to the user for authentication.
var fromAddress = new MailAddress("hamza230#gmail.com", "From Hamza");
var toAddress = new MailAddress("usama90#gmail.com", "To Usama");
const string fromPassword = "****";
const string subject = "email";
const string body = "hello world";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
String plainBody = "Title";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
message.AlternateViews.Add(plainView);
MailDefinition msg = new MailDefinition();
msg.BodyFileName = "~/newsletter.html";
msg.IsBodyHtml = true;
msg.From = "usamaazam10#gmail.com";
msg.Subject = "Subject";
ListDictionary replacements = new ListDictionary();
MailMessage msgHtml = msg.CreateMailMessage("usamaazam10#gmail.com", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
cover.ContentId = "cover";
htmlView.LinkedResources.Add(cover);
message.AlternateViews.Add(htmlView);
smtp.Send(message);
You can do this for small html pages
string smalHhtml = "<body>"
+ "your some designing"
+ "your Code : " + code
+ "</body>";
Note: This is for small body html and sending verification code via email is usually small html.
You can add the authentication code to the message body, for example:
...
message.Body = body + authenicationCode;
...
Or, if you don't create body as a const then you can create it at the top of your code, for example;
...
const string subject = "email";
string body = "Your authentication code is: " + authenicationCode;
...

Unable to send email using Mailkit from a xamarin.android app

I am not able to send email from a xamarin.android app using MailKit library of jstedfast.
I am using the following code :
try
{
//From Address
string FromAddress = "from_sender#gmail.com";
string FromAdressTitle = "Email Title";
//To Address
string ToAddress = "to_receiver#gmail.com";
string ToAdressTitle = "Address Title";
string Subject = "Subject of mail";
string BodyContent = "Body of email";
//Smtp Server
string SmtpServer = "smtp.gmail.com";
//Smtp Port Number
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("plain")
{
Text = BodyContent
};
using (var client = new SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
// Note: only needed if the SMTP server requires authentication
// Error 5.5.1 Authentication
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("from_sender#gmail.com", "password");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
Console.ReadLine();
client.Disconnect(true);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
When I run this code from my app, it throws an exception:
MailKit.Security.AuthenticationException
What I am missing in this code. Can anybody help me out !
Use MAILMESSAGE class.
using System.Net.Mail;
.
MailMessage mail = new MailMessage("example#gmail.com", "example#gmail.com", "Title","Body");
SmtpClient client = new SmtpClient();
client.Host = ("smtp.gmail.com");
client.Port = 587; //smtp port for SSL
client.Credentials = new System.Net.NetworkCredential("example#gmail.com", "password");
client.EnableSsl = true; //for gmail SSL must be true
client.Send(mail);

SmtpClient cannot send email

I try two application, one in java and one in C#. The java application can send email successfully but the C# cannot. Here is the two apps :
1.Java
final String username = "myaccount#mydomain";
final String password = "mypassword";
String smtpHost = "smtp.mydomain";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(username));
message.setSubject("Test send email");
message.setText("Hi you!");
Transport.send(message);
2.C#
string username = "myaccount#mydomain";
string password = "mypassword";
string smtpHost = "smtp.mydomain";
SmtpClient mailClient = new SmtpClient(smtpHost, 465);
mailClient.Host = smtpHost;
mailClient.Credentials = new NetworkCredential(username, password);
mailClient.EnableSsl = true;
MailMessage message = new MailMessage(username, username, "test send email", "hi u");
mailClient.Send(message);
So, what is the mistake i made in C# application? Why it cannot send email?
EDIT:
I have read this question How can I send emails through SSL SMTP with the .NET Framework? and it works. The deprecated System.Web.Mail.SmtpMail works but System.Net.Mail.SmtpClient doesn't. Why ?
3.This C# code work fine :
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver","smtp.mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "myaccount#mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
myMail.From = "myaccount#mydomain";
myMail.To = "myaccount#mydomain";
myMail.Subject = "new code";
myMail.BodyFormat = System.Web.Mail.MailFormat.Html;
myMail.Body = "new body";
System.Web.Mail.SmtpMail.SmtpServer = "smtp.mydomain:465";
System.Web.Mail.SmtpMail.Send(myMail);
The .NET System.Net.Mail.SmtpClient class cannot handle implicit SSL connection. Implicit SSL connections are sent over Port 465, as the client is configured in your example.
You can use a third party library like AIM (Aegis Implicit Mail) to send implicit SSL messages.
You can try this code as well. Also sends the email in a seperate thread.
using System.Net.Mail;
public static void Email(string Content, string To, string Subject, List<string> Attach = null, string User = "sender#sender.com", string Password = "MyPassword", string Host = "mail.sender.com", ushort Port = 587, bool SSL = false)
{
var Task = new System.Threading.Tasks.Task(() =>
{
try
{
MailMessage Mail = new MailMessage();
Mail.From = new MailAddress(User);
Mail.To.Add(To);
Mail.Subject = Subject;
Mail.Body = Content;
if (null != Attach) Attach.ForEach(x => Mail.Attachments.Add(new System.Net.Mail.Attachment(x)));
SmtpClient Server = new SmtpClient(Host);
Server.Port = Port;
Server.Credentials = new System.Net.NetworkCredential(User, Password);
Server.EnableSsl = SSL;
Server.Send(Mail);
}
catch (Exception e)
{
MessageBox.Show("Email send failed.");
}
});
Task.Start();
}

C# code for sending email in mvc4 doubts

am am doing a website in mvc4 using c#. currently i test this in localhost. I want to send passwords to registering persons email. i use the following code.
//model
public void SendPasswordToMail(string newpwd,string email)
{
string mailcontent ="Your password is "+ newpwd;
string toemail = email.Trim();
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("paru.mr#gmail.com");
mail.To.Add(toemail);
mail.Subject = "Your New Password";
mail.Body = mailcontent;
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password"); //is that NetworkCredential
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception e)
{
throw e;
}
}
//controller
string newpwd;
[HttpPost]
public ActionResult SendPassword(int Id,string email)
{
bool IsMember=CheckMember(Id);
if (IsMember == true)
{
newpwd = new Member().RandomPaswordGen();
}
.......//here i want to call that model
return View();
}
Is the model is right or not. and what should be the return type of this model(now it is void and i dont know how this call in controller). and how to get default NetworkCredential. Please help me
Network Credential is the user name and password of the email sender (as in case of company a defualt mail address like noreply#abccompany.com).
Hence use you gmail user name and password in that case.
And you could use following code to send email.
var client = new SmtpClient()
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
};
var from = new MailAddress(Email);
var to = new MailAddress(Email);
var message = new MailMessage(from, to) { Body = Message, IsBodyHtml = IsBodyHtml };
message.Body += Environment.NewLine + Footer;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = Subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
var nc = new NetworkCredential("me#gmail.com", "password");
client.Credentials = nc;
//send email
client.Send(message);

Categories

Resources