sending email fails in C# 3.5 - c#

While sending email, I get the following error:
The device is not ready at System.Net.Mail.SmtpClient.Send(MailMessage message).
The code is :
MailMessage mailMessage = new MailMessage(senderEmail, cleanRecipients)
{
Subject = string.empty,
Body = string.empty,
IsBodyHtml = false
};
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);

In order to send an email you need an SMTP server, so make sure you have specified an SMTP server in the config file.
<system.net>
<mailSettings>
<smtp from="someaddress#mydomain.com">
<network host="mail.mydomain.com" password="secret" port="25" userName="someaddress#mydomain.com" />
</smtp>
</mailSettings>
</system.net>

This code maybe will help!
string from = me#gmail.com; //Replace this with your own correct Gmail Address
string to = you#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, "Password");
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

Related

.Net smtp not sending emails, no errors

I am trying to send email through the web application using my client organisation's email server. The following is the code I am using.
MailMessage MyMailMessage = new MailMessage();
MyMailMessage.Subject = "Email testing";
MyMailMessage.From = new MailAddress("name#mydomain.com", "My name");
MyMailMessage.To.Add(new MailAddress(strEmail, "Applicant"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.EnableSsl = true;
mySmtpClient.Send(Accepted);
Web.config file:
<mailSettings>
<smtp deliveryMethod="Network" from=" name#mydomain.com">
<network host="smtps.mydomain.com" port="465" enableSsl="true" defaultCredentials="true"
userName="myName" password="myPassword" />
</smtp>
</mailSettings>
It works perfectly fine when I use gmail smtp details or my local organisation's smtp details. For some reason, its not working and neither is it throwing any errors.
I have tried debugging and checked the exception which says 'timed out'.
I am not sure what else to check. Could someone please suggest a solution.
Note: I have also checked that no firewall is blocking port:465.
Thank you.
Kind regards,
Sud
You could try to test the connection by typing "telnet smtps.mydomain.com 465" in Command Promt(cmd).
Regards
Try this one:
var sysLogin="yourlogin#gmail.com";
var sysPass="y0urP#ss";
var sysAddress = new MailAddress(sysLogin, "Message from me!");
var receiverAddress = new MailAddress("mike#hotmail.com");
var smtp = new SmtpClient
{
Host = "smtp.gmail.com", //gmail example
Port = 587,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(sysLogin, sysPass)
};
using (var message = new MailMessage(sysAddress, receiverAddress) { Subject = "Some subject", Body = "Some text" })
{
smtp.Send(message);
}
<system.net>
<mailSettings>
<smtp from="emialid.com">
<network host="domain.com" port="25" userName="emialid.com" password="******" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = "Your Password is : " + EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}
}
}
Have you verified that the client SMTP server has a valid SSL certificate installed and can accept connections on port 465?
If you are able to do so, run a packet sniffer such as WireShark to check the packet flow.
The SysIntenerals TcpView tool is a lighter-weight utility that would let you see the packet state as well.
Thank you all for your suggestions. I have fixed it, I just had to change the port number from 465 to 25.

Send automated e-mail to new user aspx

When someone registers on my website he/she also needs to fill in his/her e-mail address.
After clicking on the ''Register''-button the system needs to send an automated e-mail to the e-mail address which is written in the textbox.
Anyone who can help me with this?
Thanks in advance!
To send email in asp.net you will want to look into System.Net.Mail. There are two steps two send mail from within asp.net
1) Email Account Settings - This can be set up globally in your web.config file
<system.net>
<mailSettings>
<smtp from="test#foo.com">
<network host="host" port="25" userName="username" password="password" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
2) Setting up your message - In your register pages code behind
MailMessage message = new MailMessage();
message.From = new MailAddress("sender#sender.com");
message.To.Add(new MailAddress("email#email.com"));
message.Subject = "subject";
message.Body = "content";
SmtpClient client = new SmtpClient();
client.Send(message);
http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx
Here is a simple instruction on how to send e-mail from .NET code: http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx
The main keyword you are looking for is System.Net.Mail.
The following script is a good starting place.
using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) {
System.Text.StringBuilder body = new System.Text.StringBuilder("Your message");
System.Net.Mail.SmtpClient() smtp = new System.Net.Mail.SmtpClient();
mail.To.Add("yourUser#email.com");
mail.From = new System.Net.Mail.MailAddress("yourFrom#email.com");
mail.Subject = "a Subject";
mail.Body = body.ToString();
try {
smtp.Send(mail);
} catch (Exception ex) {
// handle your exception here..
}
}
This assumes that you have some details in your config about the SmtpClient. Like this: http://msdn.microsoft.com/en-us/library/ms164240.aspx
If not, then you can provide the details to the client in the SmtpClient() constuctor. More info on that here: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
Here is a simple function to implement. You have to get network credentials if not anonymous and SMTP info about your SMTP relay server. Otherwise it should be straight forward.
using System.Net.Mail; //goes on top
//goes in your class
public void sendEmail(string emailMessage,
string emailSubject,
string emailAddress, string from,
string fromAddress, string emailCC,
string emailBCC)
{
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(fromAddress, from);
msg.To.Add(emailAddress);
if (emailCC != null && emailCC.ToString().Length > 1)
msg.CC.Add(emailCC);
if (emailBCC != null && emailBCC.ToString().Length > 1)
msg.Bcc.Add(emailBCC);
msg.Priority = MailPriority.High;
msg.Subject = emailSubject;
msg.Body = emailMessage;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = info.SMTPServer;
client.Port = 25;
client.EnableSsl = true;
// client.UseDefaultCredentials = some System.Net.NetworkCredential var;
client.Credentials = info.networkCredentials;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// Use SendAsync to send the message asynchronously
client.Send(msg);
}
catch
{
//handle exception
}
}
USAGE & Implementation:
this.sendEmail("test message", "your subject", "to#to.com","from person", "from#from.com","cc#cc.com","bcc#bcc.com");

How to send mail through C# asp.net for contact form

I am trying to create contact form to send email (from and to will be from user interface):
try {
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("fromadd");
mail.To.Add("toadd");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username","password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
This works for only Gmail - however, I would like to make it work for any email provider - how would I go about this?
You should configure the SmtpClient in the web.config:
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
Then in your code you can do:
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("fromadd");
mail.To.Add("toadd");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
You can set up your SmtpClient configuration in your web.config. This will make it flexible.
http://blog.dotnetclr.com/archive/2009/08/18/511.aspx
http://msdn.microsoft.com/en-us/library/w355a94k.aspx
Don't use hardcoded parameters for the connection to the smtp-server.
Use the webconfig instead. Your program will be more "generic". Just alter the config when you want to send through another smtp-server
You can also try:
MailMessage msgObj = new MailMessage();
msgObj.To = "example#example.com";
msgObj.From = "Mike";
msgObj.Bcc = "example#example.com";
msgObj.Subject = "Test Message";
msgObj.Body = "Hello World!";
SmtpMail.SmtpServer = "Your Server";
SmtpMail.Send("FromEmail", "ToEmail", "Subject", "Query");
SmtpMail.Send(msgObj);
To me it looks like the only thing that might be preventing you from sending the email using any email server is the fact that some mail servers require authentication (or possibly an alternative port number).
Here is a bit of basic code that should get you pointed in the right direction
public class SendMail
{
public SendMail(string SMTPServer, string fromEmail)
{
this.SMTPServer = SMTPServer;
this.FromEmail = fromEmail;
}
public SendMail(string SMTPServer, string fromEmail, string Username, string Password) : this(SMTPServer, fromEmail)
{
this.Username = Username;
this.Password = Password;
}
public string SMTPServer { get; set; }
public string FromEmail { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public void Send(string toEmail, string subject, string data)
{
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add(toEmail);
MailAddress mailAddress = new MailAddress(this.FromEmail);
mailMsg.From = mailAddress;
mailMsg.Subject = subject;
mailMsg.Body = data;
mailMsg.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient(this.SMTPServer, 25);
if (this.Username.Length > 0 && this.Password.Length > 0)
{
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(this.Username, this.Password);
smtpClient.Credentials = credentials;
}
smtpClient.Send(mailMsg);
}
}
i am trying this code .
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("best#technosys.com");
mail.To.Add("best#technosys.com");
mail.Subject = "Accept Request";
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Credentials = new System.Net.NetworkCredential("best#technosys.com", " password");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
catch (Exception ex)
{
ViewData.ModelState.AddModelError("_FORM", ex.ToString());
}

Unable to send email using Gmail

I am trying to send email using gmail from my mvc application. I am getting the following exception
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
here is the code for sending email
string tn = "EmailVerification.htm";
string fileName = Path.GetFileName(tn);
string templatePath = Path.Combine(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates")), fileName);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new MailAddress(EmailFrom, "Email");
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = "subject";
mailMessage.IsBodyHtml = true;
MailDefinition mailDef = new MailDefinition();
mailDef.BodyFileName = templatePath;
mailDef.IsBodyHtml = true;
mailDef.Subject = "mailDefsubject";
mailDef.From = mailMessage.From.ToString();
ListDictionary replacements = new ListDictionary();
replacements.Add("<%FIRSTNAME%>", FirstName);
replacements.Add("<%USERNAME%>", "asd");
replacements.Add("<%VERIFICATIONLINK%>", VerificationLink);
replacements.Add("<%WEBSITE%>", "http://www.mysite.com");
MailMessage msgHtml = mailDef.CreateMailMessage(To, replacements, new System.Web.UI.Control());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, null, "text/html");
AddLinkedResources(templatePath, ref htmlView);
mailMessage.AlternateViews.Add(htmlView);
SmtpClient smtpClient = new SmtpClient();
Object userState = mailMessage;
smtpClient.Credentials = new System.Net.NetworkCredential("myaddress#gmail.com", "1234567");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
//Attach event handler for async callback
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.Send(mailMessage);
EmailStatus = true;
}
catch (SmtpException smtpEx)
{
EmailStatus = false;
}
catch (Exception ex)
{
//HttpContext.Current.Response.Write(ex.InnerException);
EmailStatus = false;
}
in the web.config i have
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="noreply#asd.com">
<network host="smtp.gmail.com" port="587"
userName="asd#gmail.com"
password="asd" />
</smtp>
</mailSettings>
</system.net>
Try setting:
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("myaddress#gmail.com", "1234567");
Also you seem to be subscribing to the SendCompleted event but this event is intended to be used when sending an email asynchronously (SendAsync method), so you could get rid of it. The Send method that you are using is blocking.
You may also checkout the following answer.

Problem in Sending Email using Gmail Settings

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;
}
}

Categories

Resources