I am using below code in c#,
string Subject = "test12";
MailMessage mail = new MailMessage();
mail.To.Add(item.ToString());
mail.From = new MailAddress(EmailUserName);
mail.Subject = Subject;
mail.Body = PopulateBody();
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient(EmailHost, EmailPort);
client.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential(EmailUserName, EmailPassword);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
I am getting error in Client.send(mail) method
What I have tried:
System.Security.Authentication.AuthenticationException: A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The function requested is not supported
--- End of inner exception stack trace ---
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at
I would try without authentication first to check if that gives a different error and also try without ssl.
protected bool NotifyByMail(string server, string strFrom, string strTo, string strSubject, string strBodyText, bool isBodyTextHtml = false)
{
if (string.IsNullOrEmpty (server)
|| string.IsNullOrEmpty (strFrom)
|| string.IsNullOrEmpty (strTo)
|| string.IsNullOrEmpty (strSubject)
|| string.IsNullOrEmpty (strBodyText))
return false;
try {
MailAddress from = new MailAddress (strFrom);
MailAddress to = new MailAddress (strTo);
MailMessage message = new MailMessage (from, to);
message.Subject = strSubject;
message.Body = strBodyText;
message.IsBodyHtml = isBodyTextHtml;
SmtpClient client = new SmtpClient (server);
// Include credentials if the server requires them.
//client.Credentials = new System.Net.NetworkCredential ("********", "*******");// System.Net.CredentialCache.DefaultNetworkCredentials;
client.Send (message);
return true;
}
catch (Exception exception) {
// TODO ErrorHandling
}
return false;
}
Related
I am trying to send mail with multiple attachment in c# but I am getting this error
A recipient must be specified while sending mail
Here is my code for sending mail with attachment
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
if (fileuploading.HasFile)//Attaching document
{
string FileNamess = fileuploading.PostedFile.FileName;
string FileName = Path.GetFileName(fileuploading.PostedFile.FileName);
message.Attachments.Add(new System.Net.Mail.Attachment(fileuploading.PostedFile.InputStream,FileName));
}
string mailbody = editor.Text;
message.Subject = txtsubject.Text;
message.Body = mailbody;
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("xxx#mail.com","xxxxx");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
}
catch (Exception ex)
{
throw ex;
}
You have an unused string "to". You need to add this string to recipient list message.To.
To do that refer following snippet;
string to = txtto.Text; //To address
string from = "xxx#mail.com"; //From address
MailMessage message = new MailMessage();
message.From = new MailAddress(from);
message.To.Add(to); //Add this line to your code
For above example to work, your string to should contain a recipient address in format "xxx#mail.com".
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
This mail code is working in localhost i.e on my computer but when i uopload it on server it is not working.
The error is : Failure sending mail. please tell me where is the problem.
if (Session["userinfo"] != null)
{
lblTest.Text = Session["userinfo"].ToString();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("shop.bcharya#gmail.com");
msg.To.Add(new MailAddress("bcc#dr.com"));
msg.To.Add(new MailAddress("info#yzentech.com"));
msg.Subject = "Mail from BcharyaCorporation.online shopping site";
msg.Body = ""+lblTest.Text+" wants to buy some products. please contact with him/her";
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
// sc.Port = 25;
sc.Credentials = new NetworkCredential("shop.bcharya#gmail.com", "mypassword");
sc.EnableSsl = true;
try
{
sc.Send(msg);
lblPayment.Text = "Sorry. Currently we are out of online payment service. We will contact you for payment process. Thank you for buying this product.";
}
catch (Exception ex)
{
lblPayment.Text=ex.Message.ToString();
Response.Write(ex.Message);
}
}
For gmail mail settings add Port number too
sc.Port = 587;
after this line
sc.Host = "smtp.gmail.com";
Only use port 587 and SSL if the SMTP server supports that (GMail and Hotmail for example). Some servers just use port 25 and no SSL.
Use below method and then check :
SmtpClient sc = new SmtpClient(string); //sends e-mail by using the specified SMTP server
You can use this below given code for sending email. Here sending the error details through email is one method. Try this code for sending email.
using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail#domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail#domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}
Does .NET 4 has any problems in sending emails? I had a .NET 3.5 solution and it was working then migrated the solution to .NET 4 and It does not works; nothing changed!
Notes:
I get this exception:
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.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ...
And this is my code:
public static void SendEmail(
this Email email)
{
if (email.MailingSettings == null) throw new ArgumentNullException("email.MailingSettings", "specify email.MailingSettings");
var settings = email.MailingSettings;
if (string.IsNullOrEmpty(email.Sender)) throw new ArgumentException("email.Sender", "specify a sender");
if (email.Recipients == null) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (email.Recipients.Length == 0) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
if (string.IsNullOrEmpty(settings.SMTPHost)) throw new ArgumentException("email.SMTPHost", "specify email.SMTPHost");
var mail = new MailMessage();
if (string.IsNullOrEmpty(email.SenderDisplayName))
mail.From = new MailAddress(email.Sender);
else
mail.From = new MailAddress(email.Sender, email.SenderDisplayName);
if (!string.IsNullOrEmpty(email.ReplyTo))
{
if (string.IsNullOrEmpty(email.ReplyToDisplayName))
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo));
}
else
{
mail.ReplyToList.Add(new MailAddress(email.ReplyTo, email.ReplyToDisplayName));
}
}
foreach (string recipient in email.Recipients)
mail.To.Add(new MailAddress(recipient));
mail.Subject = email.Subject;
mail.Body = email.Body;
mail.IsBodyHtml = settings.IsBodyHtml;
if (email.CC != null && email.CC.Length > 0)
foreach (string cci in email.CC)
mail.CC.Add(cci);
if (email.BCC != null && email.BCC.Length > 0)
foreach (string bcci in email.BCC)
mail.Bcc.Add(bcci);
if (email.Attachments != null)
foreach (var ifn in email.Attachments)
mail.Attachments.Add(
new Attachment(
new MemoryStream(
ifn.Content),
ifn.FileName));
var smtpPort = settings.SMTPPort > 0 ? settings.SMTPPort : 25;
var smtpClient = new SmtpClient(settings.SMTPHost, smtpPort);
smtpClient.EnableSsl = settings.EnableSsl;
if (!string.IsNullOrEmpty(settings.SMTPUser))
{
smtpClient.UseDefaultCredentials = false;
var smtpPassword = settings.SMTPPassword == null ? string.Empty : settings.SMTPPassword;
NetworkCredential netCred;
if (string.IsNullOrEmpty(settings.SMTPDomain))
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword);
else
netCred = new NetworkCredential(settings.SMTPUser, smtpPassword, settings.SMTPDomain);
smtpClient.Credentials = netCred;
}
else
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
smtpClient.Timeout = 180 * 1000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpClient.Send(mail);
}
If everything is as per posted-code and comments then I can say that you've turned on 2-step verification of your google account and in that case you need to generate Application Specific-password.
This code is correct and works. The problem was on GMail side and solved (not detected why and how).
Try to use this :
try
{
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "senderemail#gmail.com";
string password = "password";
string emailTo = "receiver#gmail.com";
string subject = "Halo!";
string body = "Halo, Mr. SMTP";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
*Note before that you need to activated this : https://myaccount.google.com/lesssecureapps
and then build and run the code.. it's amazing.. :)
I can't send a email message using gmail settings. i already tried client.Host ="localhost" it's working but not in client.Host ="smtp.gmail.com".. Please help me guys.. I need use client.Host ="smtp.gmail.com".. thanks
here's my C# code:
string from = "aevalencia119#gmail.com"; //Replace this with your own correct Gmail Address
string to = "aevalencia191#gmail.com"; //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to); mail.From = new
MailAddress(from, "One Ghost" ,System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ; mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient(); //Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "iseedeadpoeple");
client.Port = 587; // Gmail works on this port client.Host ="smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
} HttpContext.Current.Response.Write(errorMessage
);
} // end try
here's the error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Much thanks guys!
You need to get and send mail to GMail by using SSL secutiry certificate
MailMessage msgMail = new MailMessage("a#gmail.com", "b#mail.me", "subject", "message body");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("a#gmail.com", "a");
try
{
smtp.Send(msgMail);
}
catch (Exception ex)
{
}
reference: http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/28b5a576-0da2-42c9-8de3-f2bd1f30ded4
public static string sendMail(string to, string title, string subject, string body)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
if (to == "")
to = "aevalencia119#gmail.com";
MailAddressCollection m = new MailAddressCollection();
m.Add(to);
mail.Subject = subject;
mail.From = new MailAddress( "aevalencia119#gmail.com");
mail.Body = body;
mail.IsBodyHtml = true;
mail.ReplyTo = new MailAddress("aevalencia119#gmail.com");
mail.To.Add(m[0]);
smtp.Host = "smtp.gmail.com";
client.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("aevalencia119#gmail.com", "####");
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Send(mail);
return "done";
}
catch (Exception ex)
{
return ex.Message;
}
}