How can I make SMTP authenticated in C# - c#

I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message.
How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password?

using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("from#yourdomain.com");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("to#anydomain.com");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
You may use the above code.

Ensure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false.
The order is important as setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to null.

Set the Credentials property before sending the message.

To send a message through TLS/SSL, you need to set Ssl of the SmtpClient class to true.
string to = "jane#contoso.com";
string from = "ben#contoso.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Send(message);

How do you send the message?
The classes in the System.Net.Mail namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials property.

In my case even after following all of the above. I had to upgrade my project from .net 3.5 to .net 4 to authorize against our internal exchange 2010 mail server.

Related

Sending mail through C# with gmail is not working after deploying to host

I am trying to send mail through Gmail. I am sending mail successfully when I am testing on localhost, but this does not work when I upload it to a web host. I am seeing this type of error:
Request for the permission of type System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.
Whenever I am using port 25 get this type of error below:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
Below is my code of send email.
MailMessage mail = new MailMessage("host#gmail.com","User#gamil.com");
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.Subject = "Any String"
mail.Body = mailbody;
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("xyz#gmail.com","123");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Is there any solution? Please suggest to me!
Edit: OP Added extra information crucial to answering this question, but I'm keeping the old answer around as it might still help someone
New Answer:
This StackOverflow question already answered this question
OldAnswer:
As this StackOverflow answer already answered, you changed the Port on the SMTP Server to 587 instead of its default (25) and this requires elevated permissions causing this error change this:
SmtpServer.Port = 587;
to this:
SmtpServer.Port = 25;
and it should work
Note: When using SSL the port needs to be 443
Answer : Your code add SmtpDeliveryFormat.SevenBit
Example:
using (SmtpClient smtp = new SmtpClient())
{
NetworkCredential credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["UserName"],
Password = WebConfigurationManager.AppSettings["Password"],
};
smtp.Credentials = credential;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.DeliveryFormat = SmtpDeliveryFormat.SevenBit;
smtp.Host = WebConfigurationManager.AppSettings["Host"];
smtp.Port = WebConfigurationManager.AppSettings["Port"].ToNcInt();
smtp.EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"]);
smtp.Send(mail);
}
Try This
using System;
using System.Net;
using System.Net.Mail;
namespace AmazonSESSample
{
class Program
{
static void Main(string[] args)
{
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
String FROM = "a#a.com";
String FROMNAME = "ABC";
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
String TO = "a#a.com";
// Replace smtp_username with your Amazon SES SMTP user name.
String SMTP_USERNAME = "a#a.com";
// Replace smtp_password with your Amazon SES SMTP user name.
String SMTP_PASSWORD = "ASJKAJSN";
// (Optional) the name of a configuration set to use for this message.
// If you comment out this line, you also need to remove or comment out
// the "X-SES-CONFIGURATION-SET" header below.
String CONFIGSET = "ConfigSet";
// If you're using Amazon SES in a region other than US West (Oregon),
// replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
// endpoint in the appropriate AWS Region.
String HOST = "smtp-relay.sendinblue.com";
// The port you will connect to on the Amazon SES SMTP endpoint. We
// are choosing port 587 because we will use STARTTLS to encrypt
// the connection.
int PORT = 587;
// The subject line of the email
String SUBJECT =
"Amazon SES test (SMTP interface accessed using C#)";
// The body of the email
String BODY =
"<h1>Amazon SES Test</h1>" +
"<p>This email was sent through the " +
"<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
"using the .NET System.Net.Mail library.</p>";
// Create and build a new MailMessage object
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress(FROM, FROMNAME);
message.To.Add(new MailAddress(TO));
message.Subject = SUBJECT;
message.Body = BODY;
// Comment or delete the next line if you are not using a configuration set
message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);
using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Pass SMTP credentials
client.Credentials =
new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Enable SSL encryption
client.EnableSsl = true;
// Try to send the message. Show status in console.
try
{
Console.WriteLine("Attempting to send email...");
client.Send(message);
Console.WriteLine("Email sent!");
}
catch (Exception ex)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + ex.Message);
}
}
}
}
}

using gmail as smpt for deliver email from mvc controller

I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);

How do I send an email with Gmail and SmtpClient when the sending account uses two factor authentication?

SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "password");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("sender#gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>Hello, this is a demo ... ..</h1>";
message.To.Add("receiver#gmail.com");
try
{
smtpClient.Send(message);
}
catch (Exception ex)
{
//Error, could not send the message
ex.ToString();
}
// The thing is that this code works fine for gmails without phone number protection. Exception occurs when using this code with gmails that are protected(verified) via the client phone number.
One of the solution is to use a remote server to access clients mails.
Now my question is there another method to solve this issue ? other than third parties.
If I understand you correctly, you're saying the Google account is using two-factor authentication.
If that's the case, you need to create an Application Password for this. Go to https://security.google.com/settings/security/apppasswords once logged in as the account you want to two-factor auth with.
In the list, under Select App choose "Other" and give it some name. Click Generate, and write this password DOWN cause you will only ever see it ONCE. You will use this in your authentication. It will be 16-characters long and the spaces don't matter, you can include them or omit them. I included them here just because.
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

Can't send mail using SmtpClient

I want to send mail using SmtpClient class, but it not work.
Code:
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(obMailSetting.UserName, obMailSetting.Password);
smtpClient.Host = obMailSetting.HostMail;
smtpClient.Port = obMailSetting.Port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = obMailSetting.Connect_Security;//true
//smtpClient.UseDefaultCredentials = true;//It would work if i uncomment this line
smtpClient.Send(email);
It throws an exception:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
I'm sure that username and password is correct. Is there any problem in my code?
Thanks.
You can try this :
MailMessage mail = new MailMessage();
mail.Subject = "Your Subject";
mail.From = new MailAddress("senderMailAddress");
mail.To.Add("ReceiverMailAddress");
mail.Body = "Hello! your mail content goes here...";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
NetworkCredential netCre =
new NetworkCredential("SenderMailAddress","SenderPassword" );
smtp.Credentials = netCre;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
// Handle exception here
}
You can try this out :
In the Exchange Management Console, under the Server Configuration node, select Hub Transport and the name of the server. In the Receive Connectors pane, open either of the Recive Connectors (my default installation created 2) or you can create a new one just for TFS (I also tried this and it worked). For any of these connectors, open Properties and on the Permission Groups tab ensure that Anonymous Users is selected (it's not by default).
Or
You can also try this by initializing SmtpClient as follows:
SmtpClient smtp = new SmtpClient("127.0.0.1");
The server responds with 5.7.1 Client was not authenticated but only if you do not set UseDefaultCredentials to true. This indicates that the NetworkCredential that you are using is in fact wrong.
Either the user name or password is wrong or perhaps you need to specify a domain? You can use another constructor to specify the domain:
new NetworkCredential("MyUserName", "MyPassword", "MyDomain");
Or perhaps the user that you specify does not have the necessary rights to send mail on the SMTP server but then I would expect another server response.

error in sending email by yahoo smtp

i config my outlook 2010 by thie article to send and receive email from yahoo.com it works good without any problem.
i develop a small application to send my emails by my application but it gave me errors:
"unable to read data from the transport connection:an exist connection was
forcibly closed by the remote host."
my codes:
try
{
SmtpClient smtp = new SmtpClient("smtp.mail.yahoo.com", 465);
smtp.UseDefaultCredentials = true;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("myid", "mypass");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new System.Net.Mail.MailAddress("myid#yahoo.com", "blabla");
mailMessage.To.Add(new System.Net.Mail.MailAddress("xxx#live.com", "xxx#live.com"));
mailMessage.Subject = "test";
mailMessage.Body = "test";
mailMessage.IsBodyHtml = false;
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = MailPriority.High;
smtp.Send(mailMessage);
Console.WriteLine("hooooooooooraaaaaaaaaaaaaaa");
Console.ReadKey();
}
catch (Exception err)
{
Console.WriteLine(err.InnerException.Message);
Console.ReadKey();
return;
}
From MSDN
Some SMTP servers require that the client be authenticated before the
server sends e-mail on its behalf. Set this property to true when this
SmtpClient object should, if requested by the server, authenticate
using the default credentials of the currently logged on user. For
client applications, this is the desired behavior in most scenarios.
The UseDefaultCredentials = true sends to the SMTP server the credentials of the current logged in user (i.e. the Windows User) not the credentials you have defined.
Try with UseDefaultCredentials = false

Categories

Resources