How do I send an email from my C# windows application? - c#

I.m working on a Windows app where the user has to enter a password. I also have a "Forgot Password" link. on the window. When that's clicked, I have the user enter their email address and click a Submit button. Every time they enter an email address and click the button, I get the error message:
SmtpException has occured: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
The code I'm using is:
try
{
Cursor = Cursors.WaitCursor;
MailAddress from = new MailAddress("bgatt64#gmail.com", "Bob Gatto");
MailAddress to = new MailAddress("bgatto64#yahoo.com", "Bob Gatto");
MailMessage eMsg = new MailMessage(from, to);
eMsg.Subject = "Your Password Renewal Request";
eMsg.IsBodyHtml = true;
eMsg.Body = "This is the body.";
SmtpClient eClient = new SmtpClient("smtp.gmail.com", 587);
eClient.EnableSsl = true;
eClient.UseDefaultCredentials = true;gmail
// The following email and password used is that of my own gmail email
// that I use for my own personal email.
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<MyPassword>");
eClient.Send(eMsg);
}
catch (SmtpException ex)
{
throw new ApplicationException("SmtpException has occurred: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
What else needs to be done?

You cannot use your plain google account password to authenticate to Gmail SMTP server anymore as Google requires two-step authentication now.
You'll need to use the App Password instead:
Go to https://myaccount.google.com/security and turn on Two Step verification
Click "App Passwords"
Request a new password for the Mail application on the Windows Computer
You'll get the string with the 4 groups of characters. Now you need to use it in your code:
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<App Password>");
You can find more info Here

After the removal of less secure apps you can no longer use your actual google password to connect to the smpt server you need to create an apps password.
How to create a Apps Password for connecting to Google's SMTP server.
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "[redacted]#gmail.com";
private const string From = "[redacted]#gmail.com";
private const string GoogleAppPassword = "";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}
Note: if you are trying to connect users then you could also use Xoauth2 but using an apps password is far easer solution.

Related

Problem with SmtpClient in ASP.NET web app

I am having an issue with SmtpClient in an ASP.NET web application.
I have a generic function that builds an email message and then sends it. The code is as follows:
public static bool SendMessage( string fromName, string toName, string subject, string body ) {
var smtpClient = new SmtpClient("server address here")
{
Port = 587,
Credentials = new NetworkCredential("user", "pass"),
EnableSsl = false,
};
var mailMessage = new MailMessage
{
From = new MailAddress("sender", "Testing"),
Subject = subject,
Body = body
};
mailMessage.To.Add ( new MailAddress(toName, "Valued Customer") );
try {
smtpClient.Send ( mailMessage );
return true;
}
catch (Exception ex) {
var error = $"ERROR :{ex.Message}";
return false;
}
}
The problem is, I get the following error when I call it:
Mailbox unavailable. The server response was: <email address being sent to> No such user here
Naturally I removed the value in the < >, but in the original error message it is the email address of the recipient. I almost think the SMTP server believes the recipient has to be a user on the system.
What can I try next? I even hard-coded email addresses in rather than using variables, thinking maybe there was some weird issue with that, but it didn't work.
The error is telling you that the the SMTP server does not have a user with that email address (usually it has to do with security around the FROM address). The SMTP server will not send email if it does not recognize the FROM address.
Solution, change your FROM. Example:
var mailMessage = new MailMessage
{
From = new MailAddress("tester", "test#adminsystem.com"),
Subject = subject,
Body = body
};

.NET : Unable to change from in SMTP email

I'm trying to send emails in .NET over SMTP. I linked serval custom aliases to the account in office365. (For example no-reply#domain-a.com, no-reply#domain-b.com)
But the mails arrive from No-Reply#mydomain.onmicrosoft.com. Even if I pass in a custom domain in the "from" parameter.
Here is my code:
var smtpClient = new SmtpClient(_settings.Endpoint, int.Parse(_settings.Port))
{
UseDefaultCredentials = false,
EnableSsl = true,
Credentials = new NetworkCredential(_settings.UserName, _settings.Password),
};
var mailMessage = new MailMessage
{
From = new MailAddress(message.From.Email, message.From.Name),
Subject = message.Subject,
Body = message.HtmlMessage,
IsBodyHtml = true
};
foreach (var addressee in message.Tos)
{
mailMessage.To.Add(addressee.Email);
}
try
{
smtpClient.Send(mailMessage);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending email");
throw;
}
As username I'm using myaccount#mydomain.onmicrosoft.com. What am I missing here?
Nothing should be wrong with the office365/domain config cause it works when I'm trying to send the mail using powershell
$O365Cred = Get-Credential #the myaccount#mydomain.onmicrosoft.com credentials
$sendMailParams = #{
From = 'no-reply#mydomain-a.com'
To = 'me#gmail.com'
Subject = 'some subject'
Body = 'some body'
SMTPServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $O365Cred
}
Send-MailMessage #sendMailParams
Both Google (GMail) and Microsoft (Office365) replace the From header with the email address of the account used to send the mail in order to curtail spoofing.
If you do not want this, then you'll need to use another SMTP server or set up your own.
I found out that it works when sending the email to my personal Gmail. Meaning that there is nothing wrong with the code, but a configuration problem in my office365 / AD domain.
Apparently the outlook "address book" automatically fills in the "from / sender" part in the email, caused because I was sending an mail to the same domain as the one used for my SMTP account. (for example me#domain-a.com and noreply#domain-a.com).

I Can't Send Mail When I Publish My Web Site - ASP.NET Web Forms

I published the site I completed using ASP.NET Web Forms but I'm having trouble sending mail. My web site does not send mail. There is no problem when I run in local.
My Fonksiyon.cs:
public static bool MailGonder(string gonderenaciklama, string kimemail, string kimeadi, string mailkonu, string mailicerik, string kimdenmail = "", bool IletisimFormuMu = false)
{
MailAddress From = new MailAddress(IletisimFormuMu ? kimdenmail : "My e-mail address is here", gonderenaciklama); // Gönderen kısmında görünen e-posta adresi.
MailAddress To = new MailAddress(kimemail, kimeadi); // Mailin gönderileceği adres.
MailMessage EMail = new MailMessage(From, To);
EMail.Subject = mailkonu;
EMail.Body = mailicerik;
EMail.IsBodyHtml = true;
EMail.BodyEncoding = Encoding.Unicode;
SmtpClient MailClient = new SmtpClient();
MailClient.Port = 587;
MailClient.Host = "smtp.gmail.com";
MailClient.EnableSsl = true; // Gmail üzerinden gönderme yapılacaksa veya sunucu kimlik doğrulaması gerektiriyorsa buraya true değerini vereceğiz.
MailClient.UseDefaultCredentials = true;
MailClient.Credentials = new System.Net.NetworkCredential("My e-mail address is here", "My password is here"); // Maili göndereceğimiz hesap bilgileri buraya giriyoruz. Mailimiz bu hesap üzerinden gönderilecek.
MailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
MailClient.Send(EMail);
return true;
}
catch
{
return false;
}
}
My register.aspx button click:
string guid = Guid.NewGuid().ToString();
Fonksiyon.MailGonder("Ay Tasarım E-Posta Doğrulaması", TxtEPosta.Text, TxtAd.Text + " " + TxtSoyad.Text, "E-Posta Doğrulaması", "Lütfen aşağıdaki aktivasyon kodunu sitemizdeki ilgili alana yazarak üyeliğinizi aktif ediniz!<br />Aktivasyon Kodu: " + guid + "");
Nothing to do with your code, this is security feature of your gmail account.
these are the reasons that you can check
Google's security system has blocked the IP of your server
Google security system is actually pretty cool, if somebody gets his hands on your Gmail's password, well he won't be able to do much, unless he is using your IP address. Why? Because when Google spots an unusual IP address trying to connect to your account it will deny it access and will send you an email and eventually a text message on your mobile phone.
When you send a test email from MailPoet's Settings and you get the following message : " SMTP Error: Could not authenticate. | SMTP Error: Could not connect to SMTP host." then you might be entering this case scenario
The email you will receive to notify you of that unusual access will be as follow :
Allow new IP's in Google account
In your case when you setup your site to send with your Gmail account, you want to allow a new IP to use your Gmail's credentials. In order to allow a new unrecognized app simply go to https://security.google.com/settings/security/activity, find the line that concerns you and allow access.
Hope this helps to resolve your problem....

Authentication error sending SMTP Request

i'm writing a C# email application which is currently being designed for use with Gmail so I can test authentication. However I'm getting an error which doesn't seem to make much sense as I am setting SSL to true and using a user and password.
Error Message:
System.Net.Mail.SmtpException: 'The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at'
using System;
using System.Net;
using System.Net.Mail;
namespace EmailSendingProgram
{
public class EmailSendingClass
{
public static void Main(string[] args)
{
Console.WriteLine("Type your Gmail Address: ");
string from = Console.ReadLine();
Console.WriteLine("Type your Gmail Password: ");
string password = Console.ReadLine();
Console.WriteLine("Type the Email Address you wish to send to: ");
string to = Console.ReadLine();
Console.WriteLine("Type the Subject of the email: ");
string subject = Console.ReadLine();
Console.WriteLine("Type or paste in your email (either text or HTML): ");
string body = Console.ReadLine();
EmailSendingClass email = new EmailSendingClass();
email.Send(from, password, to, subject, body);
}
/// handles sending the email
/// hardcoded to work with gmail just change the CreateSmtpClient from
/// "smtp.gmail.com", 587 to whatever you want to use
public void Send(string from, string password, string to, string subject, string body)
{
var message = CreateMailMessage(from, to, subject, body);
// Host and Port setup for use with Gmail
using (SmtpClient client = CreateSmtpClient("smtp.gmail.com", 587, from, password))
{
client.Send(message);
}
}
/// Defines the SmtpClient for the mail message
/// setups up the network credentials to send the email
private SmtpClient CreateSmtpClient(string host, int port, string from, string password)
{
SmtpClient client = null;
client = new SmtpClient()
{
Host = host,
Port = port,
EnableSsl = true,
Credentials = new NetworkCredential(from, password)
};
return client;
}
/// defines what is contained in the email and where it will be sent
/// also makes all messages send as HTML
private MailMessage CreateMailMessage(string from, string to, string subject, string body)
{
MailMessage message = null;
message = new MailMessage(from, to)
{
Subject = subject,
Body = body
};
message.IsBodyHtml = true;
return message;
}
}
}
I understand that something is being done incorrectly with the authentication but I can't seem to figure out what specifically. So any help would be appreciated.
I encountered a similar problem caused by TLS 1.2 support issues. If this is your case, the simplest solution might be to target .NET 4.6.1 or higher. Other suggestions can be found here and here.
The issue wasn't the program but rather was Gmail refusing sign in from "less secure apps"
I simply clicked the secure your account button and allowed this account to be signed in from less secure apps.

How to send mails using SmtpClient and DefaultNetworkCredentials to a distribution list that only allows authenticated senders?

I'm trying to send automated emails from a C# console application from machines to clients all on the same domain via our internal Exchange 2007 server (using SMTP), but I'm hitting a snag with distribution lists that only allow authenticated senders. Basically the mails I'm sending are getting rejected by Exchange with:
#550 5.7.1 RESOLVER.RST.AuthRequired; authentication required ##rfc822;AuthTESTGroup#example.com
I'm using System.Net.Mail.SmtpClient and setting the Credentials property to System.Net.CredentialCache.DefaultNetworkCredentials, but somewhere along the line, the credentials of the account running this program (me, a valid domain user with a valid mailbox) are not getting passed down to Exchange correctly.
I'm using System.Net.CredentialCache.DefaultNetworkCredentials because I do not want to hard code a username or password (either in the code itself or in any sort of configuration file); I want the process to authenticate with our SMTP server using Windows authentication.
Here is a test program I've been using to reproduce the problem (domain names have been anonomized):
using System;
using System.Net.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var smtpClient = new SmtpClient
{
Host = "MAIL",
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
};
var mailMessage = new MailMessage
{
Body = "Testing",
From = new MailAddress(Environment.UserName + "#example.com"),
Subject = "Testing",
Priority = MailPriority.Normal
};
mailMessage.To.Add("AuthTESTGroup#example.com");
smtpClient.Send(mailMessage);
}
}
}
Whenever I run this as myself (again, I'm a valid user on the domain, with an existing mailbox on the Exchange server) I get an undeliverable bounce message from Exchange with the response:
#550 5.7.1 RESOLVER.RST.AuthRequired; authentication required ##rfc822;AuthTESTGroup#example.com
I talked to our Exchange server admin and he saw the following error from the Exchange server's event log:
Account For Which Logon Failed:
Security ID: NULL SID
Account Name:
Account Domain:
Failure Information:
Failure Reason: Unknown user name or bad password.
Status: 0xc000006d
Sub Status: 0xC0000064
Apparently that status code and sub status code translate to:
0xc000006d This is either due to a bad username or authentication information. Usually logged as status code with 0xc0000064 as substatus
0xC0000064 user name does not exist
So again, it's as if somewhere along the line, my Windows credentials are not getting passed down to the Exchange server even though I'm setting the SmtpClient.Credentials to System.Net.CredentialCache.DefaultNetworkCredentials
Any ideas?
Thanks in advance!
you need to pass username, password
here is a code snippet of how I would do it... keep in mind this is a code snippet you need to make the necessary changes to fit your Use Case
MailClient = new SmtpClient();
MailClient.Credentials = new System.Net.NetworkCredential(username, password);
below is another example but uses the server variable.. this maybe what you need to do try and let me know the server for example you can pass as your domain.com
example :
//SmtpClient client = new SmtpClient("smtp.contoso.com");//this would be server
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
public static void CreateBccTestMessage(string server)
{
MailAddress from = new MailAddress("ben#contoso.com", "Ben Miller");
MailAddress to = new MailAddress("jane#contoso.com", "Jane Clayton");
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the SmtpClient class.";
message.Body = #"Using this feature, you can send an e-mail message from an application very easily.";
MailAddress bcc = new MailAddress("manager1#contoso.com");
message.Bcc.Add(bcc);
SmtpClient client = new SmtpClient(server);
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an e-mail message to {0} and {1}.",
to.DisplayName, message.Bcc.ToString());
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
ex.ToString());
}
}

Categories

Resources