Issue sending email using Gmails SMTP server - c#

Ive written an application which sends notifications to people via email. For testing purposes im using Gmails SMTP server. Using the below code im testing but im randomly getting the below error.
I'm using smtp.gmail.com on port 587
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
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailAlertService.Email.sendMail(String subject, String body, String[] recipients, String from, String& error)
About 1 out of 5 emails generates this exception.
I'm using the same credentials and to/from address combo for every test.
Any idea if its something im doing or is it Gmails servers throwing a fit!
public bool sendMail(string subject, string body, string[] recipients, string from, ref string error)
{
bool success = recipients != null && recipients.Length > 0;
if (success)
{
SmtpClient smtpClient = new SmtpClient
{
Host = hostName,
Port = port,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(username, password)
};
using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, body))
{
Console.WriteLine(recipients[0]);
for (int i = 1; i < recipients.Length; i++)
{
Console.WriteLine(recipients[i]);
gMessage.To.Add(recipients[i]);
}
try
{
smtpClient.Send(gMessage);
success = true;
error = string.Empty;
}
catch (Exception ex)
{
success = false;
error = ex.ToString();
}
}
}
else
error = "No destination email addresses supplied";
return success;
}

Related

Setting Port / SSL / Timeout with GMail Service

Here is some code for sending a test email with the GMail API:
public bool SendTestEmail(string From, string Subject, string Body)
{
try
{
MailMessage mail = new MailMessage();
mail.Subject = Subject;
mail.Body = Body;
mail.From = new MailAddress(From);
mail.IsBodyHtml = false;
mail.To.Add(new MailAddress(From));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
var result = m_Service.Users.Messages.Send(message, "me").Execute();
}
catch (Exception ex)
{
SimpleLog.Log(ex);
return false;
}
return true;
}
It works fine. However, my email settings window in my application caters for other SMTP hosts and as a result has other settings:
Is it possible to feed to the GMail Service:
Port number
SSL/TLS mode
Server Timeout
Or don’t these apply when sending emails like this?

Email with SMTP from a VLAN

I'm trying to send an automated email from my desktop application using Visual Studio C# and SMTP. It works when directly connected to the Wi-Fi but the moment I connect to the VLAN that we set up, the SmtpClient.Send() times out.
public static void SendEmail(string toAddress, string subject, string body)
{
string senderID = "email";
const string senderPassword = "password";
try
{
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
Timeout = 30000,
};
if (IsValidEmail(toAddress))
{
MailMessage message = new MailMessage(senderID, toAddress, subject, body);
smtp.Send(message);
}
else throw new Exception();
}
catch (Exception)
{
throw;
}
}
We're using static IP, so I thought maybe it had something to do with DNS since the SMTP host isn't a specific IP.

Sending Email using live/gmail smtp

I am using C# to send email using SMTP and gmail server.
Below is the code I am using for sending email. I encounter a few errors i.e.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
public static bool SendEmail(string from, string[] to, string[] cc, string[] bcc, string subject, string body, bool isBodyHtml, List<Attachment> attachmentList)
{
try
{
var mailMessage = new MailMessage();
var smtpClient = new SmtpClient();
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(string.Join(",", to)));
if (cc != null && cc.Any())
{
mailMessage.CC.Add(new MailAddress(string.Join(",", cc)));
}
if (bcc != null && bcc.Any())
{
mailMessage.Bcc.Add(new MailAddress(string.Join(",", bcc)));
}
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
if (attachmentList != null)
{
foreach (var attachment in attachmentList)
{
mailMessage.Attachments.Add(attachment);
}
}
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587; //465
smtpClient.Credentials = new System.Net.NetworkCredential("username#email.com", "passsword");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
What am I doing wrong and how do I use gmail to send email.
You haven't set UseDefaultCredentials to false, so despite the fact you have provided credentials, the application is still trying to use your windows credentials to log into the SMTP. Try the below:
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("username#email.com", "passsword");
UseDefaultCredentials needs to be set to false before you set the new network credentials.
If you are sure that your Username and Password are correct and you are still getting the error then it means that Gmail has blocked your application.
Try turning it on from here Grant Access to Less Secure Apps

Contact Us Page

I have a Contact Us page that is not working. there is this error:
System.Net.Mail.SmtpException: Mailbox unavailable. The server
response was: From domain must match authenticated domain at
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,
String response) at System.Net.Mail.MailCommand.Send(SmtpConnection
conn, Byte[] command, MailAddress from, Boolean allowUnicode) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddress
Collection recipients, String deliveryNotify, Boolean allowUnicode,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message) at
Pages_Public_Contact.btnSend_Click(Object sender, EventArgs e) in
c:\Users\Vanguardo66\Documents\Visual Studio
2013\WebSites\TelerikWebSite2\Pages\Public\Contact.aspx.cs:line 27
and this is my code-behind:
if (Page.IsValid)
{
try
{
MailMessage mail = new MailMessage((Session["User"] == "Guest" ? txtFromUnknown.Text.Trim() : UserCheck.ReturnUserInfo(4)), "ops#gitamarine.com", "Visiting", txtText.Text.Trim());
SmtpClient smtp = new SmtpClient("mail.gitamarine.com");
smtp.EnableSsl = false;
smtp.Credentials = new System.Net.NetworkCredential("website#gitamarine.com", "*********");
smtp.Port = 2525;
smtp.Send(mail);
}
catch (Exception ex)
{
lblAlert.Text = "Error: " + ex.ToString();
}
}
So I tried this but no luck!!! how does it work? I don't know!!!
any way I am new to this please help.
The error states the problem From domain must match authenticated domain you can't set the from address to the users email address, this would require an open relay mail server. Use the same from address that you used to do authentication

SmtpException While sending mails in a bulk of 3 or more

I am using SmtpClient to send emails.I am using the same code for last 2years,but from last day when i send 3 or more emails together one of them will fail.When i sent the failed one again it will sent out.Please help me i am using aibn.com mail server.
public bool SendMail(string p_strFrom, string p_strDisplayName, string p_strTo, string p_strSubject, string p_strMessage , string strFileName)
{
try
{
p_strDisplayName = _DisplayName;
string smtpserver = _SmtpServer;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(_From,_DisplayName);
smtpClient.Host = _SmtpServer;
smtpClient.Port = Convert.ToInt32(_Port);
string strAuth_UserName = _UserName;
string strAuth_Password = _Password;
if (strAuth_UserName != null)
{
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strAuth_UserName, strAuth_Password);
smtpClient.UseDefaultCredentials = false;
if (_SSL)
{
smtpClient.EnableSsl = true;
}
smtpClient.Credentials = SMTPUserInfo;
}
message.From = fromAddress;
message.Subject = p_strSubject;
message.IsBodyHtml = true;
message.Body = p_strMessage;
message.To.Add(p_strTo);
try
{
smtpClient.Send(message);
Log.WriteSpecialLog("smtpClient mail sending first try success", "");
}
catch (Exception ee)
{
Log.WriteSpecialLog("smtpClient mail sending first try Failed : " + ee.ToString(), "");
return false;
}
return true;
}
catch (Exception ex)
{
Log.WriteLog("smtpClient mail sending overall failed : " + ex.ToString());
return false;
}
}
Got the following error message
smtpClient mail sending Failed :
System.Net.Mail.SmtpException:
Failure sending mail.
System.NullReferenceException:
Object reference not set to an instance of an object.
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of Inner Exception Stack Trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
I have changed my mail server and now it is working fine.May be it depends by some mail service restriction to prevent flooding and/or spam.

Categories

Resources