SmtpClient cannot send email - c#

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();
}

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);
}
}
}

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);

Using System.Net.Mail to send email from Database list of user

I have the following email function that sends an email to a list of users. I add the users with the method message.To.Add(new MailAddress("UserList#email.com")):
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.To.Add(new MailAddress("UserList#email.com"));
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
But, how can I connect to a SQL-Server Db and get the list of users from a table, instead of from this function? Thanks for the help!
I figured it out myself in the most simple way. I hope this help someone else. Thanks to everybody who responded with positive comments, have the ability to think, and use common sense.
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
SqlCommand cmd = null;
string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
string queryString = #"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
message.To.Add(to);
}
// Passing values to smtp object
smtp.Send(message);
// Call Close when done reading.
reader.Close();
}
}
You could create this utilities.cs file in your current project and paste in the following code and see how much easier it is to read
public class utilities
{
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
}
public static string EmailRecips
{
get
{
return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA#SomeEmail.com|PersonB#SomeEmail.com|Person3#SomeEmail.com"/>
}
}
public static string EmailHost //add and entry in the config file for EmailHost
{
get
{
return ConfigurationManager.AppSettings["EmailHost"];
}
}
public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
{
using (var client = new SmtpClient(utilities.EmailHost, 25))
using (var message = new MailMessage()
{
From = new MailAddress(utilities.FromEmail),
Subject = subject,
Body = body
})
{
//client.EnableSsl = true; //uncomment if you really use SSL
//client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
//client.Credentials = new NetworkCredential(fromAddress, fromPassword);
foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
message.To.Add(address);
client.Send(message);
}
}
}
//if you want to pass a List and join into a single string of Pipe Delimited string to use in the .Split Function then you can change the method signature to take a string and pass in this to the email for example
var emailList = string.Join("|", YourList<T>);
//then the new email function signature would look like this
public static void SendEmail(string subject, string body, string emailList)
//then you would replace the .Split method with this
foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
You can do a lot to optimize and generalize the code below - it's as close to your code as possible while doing what you want. It's up to you to figure out how to connect to your database and get the DataReader.Read(). Try -- if you get stuck, ask something specific.
Using System.Net.Mail
protected void SendMail()
{
Dictionary<string,string> recipients = new Dictionary<string,string>
//--select FirstName, Email form MyClients
//while reader.Read(){
recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
//}
//Mail notification
foreach(KeyValuePair<string,string> kvp in recipients){
MailMessage message = new MailMessage();
message.To.Add(new MailAddress(kvp.Value));
message.Subject = "Hello, "+kvp.Key;
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(message);
}
} //This bracket was outside the code box

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);

Sending html template via amazon ses

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);
}

Categories

Resources