Unable to send email in asp.net C# - c#

I understand this topic has been well elaborated previously, but I have looked around the Internet for various solutions and nothing has helped so far.
I'm making a web application which at one point is supposed to send an email to the email that the user provided. I'm trying to send it from my gmail account.
I tried the following:
public void test()
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mygmail#gmail.com", "password*"),
EnableSsl = true
};
client.Send("mygmail#gmail.com", "mygmail#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
And I'm getting the following error: The server response was: 5.5.1 Authentication Required.
In my web.config file I wrote
<system.net>
<mailSettings>
<smtp>
<network host="smtp.google.com" password="" userName=""/>
</smtp>
</mailSettings>
</system.net>
But that didn't work. I also tried adding the password* and the username (mygmail#gmail.com) in the web.config instead of the empty strings for userName and password, but I still got the same error.
Could anyone please help me out?
Thank you.

Try setting UseDefaultCredentials to false before specifying your custom credentials.
See c# SmtpClient class not able to send email using gmail

Related

smptclient: sending mails using emails saved in membership table

I am working in a feature where the user is able to send mail using a asp.net webApp. The idea is send mail using address saved in their membership table. With the current code bellow what i am getting are sent mails using the address testUser#gmail.com, but what i want is send mails using the email address stored in the membership table.
Thank in advance.
var email = new MailMessage(mailContent.From, mailContent.To, mailContent.Subject, mailContent.Body);
public static SendEmailResult SendEmail(MailMessage message)
{
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
var mailClient = new SmtpClient();
var log = new SendEmailResult() { Message = message };
try
{
mailClient.Send(message);
}
catch (Exception ex)
{
log.Exception = ex;
}
return log;
}
My web config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network enableSsl="true"
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
userName="testUser#gmail.com"
password="myultrasecretpassword" />
</smtp>
</mailSettings>
</system.net>
Fortunately I think it's not possible to just send an e-mail in the name of someone else (using someone else's credentials).
As #DGibbs shows, you'd need to know the credentials of the particular user. But you don't have the password.
The SMTP protocol alone wouldn't prevent you to use any kind of sender e-mail address in the "From" field, but the .NET SmtpClient will throw an exception (SmtpException http://msdn.microsoft.com/en-us/library/swas0fwc.aspx).
The SmtpClient actually will only willing to send the e-mail if the running software's (or provided by NetworkCredentials) credentials match the from address's user.
If you use UseDefaultCredentials, the credentials (of the default) should still match the e-mail address's user and should be authorized.
What you can do is to setup a mail account for the purpose of automated mail. Even in this case there's a good chance that the software will run in the name of some other user, so system administrator has to configure that automated mail account in the mail server so that it would willing to let the software's user to send in the name of the automated account. The automated mail's subject or body can reference the user's name and e-mail if you like.
All of this is because today there are lot of mechanisms exist to prevent spamming. The system prevents you even from yourself to do anything which wouldn't be a good idea. Sending an e-mail in whoever's name is not a good idea from security point of view, even if the business requirements would require it.
System.Net.Mail provides a very clean and nice interface and API, but you have to work around the usage what you want. I've been there, done that. I mean the same situation.
Once you have the users details from the Membership table (it's up to you to do this) you can specify some credentials for the SMTP client before sending:
var mailClient = new SmtpClient();
mailClient.Credentials = new System.Net.NetworkCredential("username", "password");
//etc...

Sending email from web site using Google Apps account

Been researching this issue for quite a while, but have yet to find any solution.
I can send email from the website using my regular gmail account using smtp.gmail.com as my host and port 587.
My current problem is that there's no problem sending the mail. I no longer receive an error. However, the email is never sent. Anyone have any ideas?
Here's the code:
Config:
<smtp from="admin#domain.com">
<network host="smtp.gmail.com" password="password" userName="admin#domain.com" port="587"/>
</smtp>
Code:
public void Send() {
bool bDev = ConfigurationManager.AppSettings["dev"] == "true";
MailMessage oMsg = new MailMessage();
foreach (string sAddress in To) {
if (sAddress != "") oMsg.To.Add(sAddress);
}
oMsg.From = ((FromName == null) || (FromName == "")) ?
new MailAddress(From) :
new MailAddress(From, FromName);
oMsg.Subject = Subject;
oMsg.Body = Body.ToString();
oMsg.IsBodyHtml = true;
oMsg.BodyEncoding = Encoding.UTF8;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = (new int[] { 587, 465 }).Contains(smtp.Port);
smtp.Send(oMsg);
}
I added a second To address and resumed testing. I began to receive email to both accounts. Then after removing the second address, it started working.
I ran into a new issue where my reply-to address was using the From address. So, I added additional code to set the reply address to that of the person's email address from my form.
Code
if (!string.IsNullOrEmpty(ReplyToAddress))
oMsg.ReplyTo = new MailAddress(ReplyToAddress);
However, I ran into an issue with Gmail ignoring my defined reply-to address, and using my from address. Apparently this is by design. I couldn't find any useful information on how to override this setting, so instead I did a workaround that might prove to be helpful to anyone else having this issue.
I created a generic email address with gmail (website#gmail.com) and setup a filter. Any emails coming from admin#domain.com need to be redirected to admin#domain.com.
Now, when I run my tests, all the emails are going where they are supposed to go AND the reply to field works great.
Not the best solution as it involves me remembering to setup a new account every time I run into this issue, but it's a solution that works for the time being until a better alternative comes up.
Had exactly same issue, that no error happened but also no email was sent. Google sometimes blocks your account(usually during testing). Try logging in into gmail account and see what it says.
UPD1: also check your sent folder in gmail.
UPD2: Also make sure that "From" email is the same as your gmail email address.

SmtpException: The client or server is only configured for e-mail addresses with ASCII local-parts

The SmtpClient.Send() method is throwing this exception when I try to send an email to an address containing an accentuated character (é):
System.Net.Mail.SmtpException: The client or server is only configured
for e-mail addresses with ASCII local-parts: léo.xxx#example.com.
at System.Net.Mail.MailAddress.GetAddress(Boolean allowUnicode)
at System.Net.Mail.SmtpClient.ValidateUnicodeRequirement(MailMessage...)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
The formulation of the message makes me thing there might be a setting that I can activate to make this work, though I haven't found anything on this subject.
I have tried several SMTP servers, including Gmail. Here are the relevant bits for a repro:
Code
var msg = new MailMessage();
msg.Subject = "Test";
msg.From = new MailAddress("xxx#gmail.com");
msg.To.Add(new MailAddress("léo.yyy#gmail.com"));
new SmtpClient().Send(msg);
app.config
<system.net>
<mailSettings>
<smtp from="xxx#gmail.com">
<network host="smtp.gmail.com" port="587" userName="xxx#gmail.com" password="password" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
If the DeliveryFormat property of your SmtpClient instance is set to SmtpDeliveryFormat.SevenBit (the default) then you need to make sure your SMTP gateway is replying with SMTPUTF8 when sent EHLO by .NET while it's trying to send the email. SmtpClient uses this to work out if the gateway is able to support UTF8.
According to the source for both .NET Framework 4.5+ and .NET core, the receiving server must support UTF8 and the DeliveryFormat must be set to SmtpDeliveryFormat.International in order to be able to send.
For the latest logic and full details, see IsUnicodeSupported in:
Current .NET source
.NET Framework reference source
Late answer, but, I solved this by specifying encoding like this:
var mailMessage = new MailMessage
{
From = new MailAddress("test#domain.co.zw", "Test User", Encoding.UTF8)
}
In my case, the server was causing the error.
The below code worked for me.
SmtpClient smtpClient = new SmtpClient(SMTPServer, SMTPPort)
{
Credentials = new NetworkCredential("SMTPUserName", "SMTPPassword"),
EnableSsl = true,
DeliveryFormat = SmtpDeliveryFormat.International,
};
.net only supports ASCII characters. I don't believe it supports extended ASCII characters (which includes the accented e in question).
http://www.asciitable.com/
We ran into the same issues with users trying to use the danish character for a / e.

Proper way to pass username/password to SmtpClient (.NET)

The question is too simple, but still appreciate the short answer. I would like the SmtpClient to fetch username/password from the App.config file. From the MSDN/schema I've figured out that the proper file (excerpt) should look like:
<system.net>
<mailSettings>
<smtp from="foo#bar.com">
<network
host="mail.bar.com"
port="25"
userName="foouser"
password="barpassword"
/>
</smtp>
</mailSettings>
</system.net>
I am trying to find the proper API to call, when initializing SmtpClient state, so that mail and password will be nicely fetched from the XML:
var client = new SmtpClient( ... ); // how to fetch the servername?
client.Credentials = new NetworkCredential( ... , ... ); // how to fetch user/pass
client.Send(message);
Is there a proper/dedicated way to fetch servername, user, password or should I just call the "regular" API like ConfigurationManager.AppSettings["server"]?
Nothing special is needed, just initialize and send :)
SmtpClient client = new SmtpClient();
client.Send(mymessagehere);
That is all, it will pull from the config.

Can't override "From" address in MailMessage class using .config login credentials

I'm updating some existing code that sends a simple email using .Net's SMTP classes. Sample code is below. The SMTP host is google and login info is contained in the App.config as shown below (obviously not real login info :)).
The problem I'm having, and I haven't been able to find any answers Googling, is that I can NOT override the display of the "from" email address that's contained in the "username" attribute off the Network element in the config in the delivered email.
In the line below that explicitly sets the From property off the myMailMessage object, that value, "Sparky#myDomain.com" does NOT display when the email is received. It still shows as "erroruser#myDomain.com" from the Network tag. However, the From name "Sparky" does appear in the email.
I've tried adding a custom "From" header to the Header property of the myMailMessage but that didn't work either.
Is there anyway to login to the smtp server, as shown below using the Network tag credentials, but in the actual email received override the From email address that's displayed?
Sample code:
MailMessage myMailMessage = new MailMessage();
myMailMessage.Subject = "My New Mail";
myMailMessage.Body = "This is my test mail to check";
myMailMessage.From = new MailAddress("Sparky#MyDomain.com", "Sparky");
myMailMessage.To.Add(new MailAddress("receiver#MyDomain.com", "receiver name"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMailMessage);
in App.config:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="errors#mydomain.com">
<network host="smtp.gmail.com" port="587" userName="erroruser#mydomain.com" password="mypassword" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
This is dependent on the SMTP server. Google's SMTP server does not allow you to create your own "from" field, but I have found other SMTP servers that will. Is it necessary that you use Google's server?

Categories

Resources