.Net smtp not sending emails, no errors - c#

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.

Related

Trouble sending email in mvc application

Having some trouble sending email from my application..
I get the following Exception
An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code
Additional information: Failure sending mail.
The exception pops up when running: smtpClient.Send(mailMessage);
Function that should send mail:
public static void SendEmail(string toAddress, string subject, string body, bool isBodyHtml = true)
{
var mailMessage = new MailMessage();
mailMessage.To.Add(toAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = isBodyHtml;
var smtpClient = new SmtpClient { EnableSsl = false };
smtpClient.Send(mailMessage);
}
WebConfig configuration
<system.net>
<mailSettings>
<!-- Method#1: Send emails over the network -->
<smtp deliveryMethod="Network" from="myusername#gmail.com">
<network host="gmail.com" userName="myusername" password="mypw" port="465" />
</smtp>
</mailSettings>
</system.net>
Any help appreciated
This is how im sending gmail:
static void SendMail(string sSubject, string sBody)
{
const string senderID = "ImTheSender#gmail.com"; // use sender's email id here..
const string toAddress = "ImTheRecip#gmail.com";
const string senderPassword = "passwords are fun"; // sender password here...
try
{
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com", // smtp server address here...
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
Timeout = 30000,
};
MailMessage message = new MailMessage(senderID, toAddress, sSubject, sBody);
smtp.Send(message);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
LogThis("Error sending mail:" + ex.Message);
Console.ResetColor();
}
}

Unable to connect to remote server

I am new to C# and I am trying to send an email from a desktop program I am developing. Here is the code I am using but I keep getting the error below :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("thesma#gmail.com");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("ideas#gmail.com");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com",578);
smtp.EnableSsl = true;
smtp.Send(message);
I can't seem to find out what the problem is...
You need to set the credentials for Gmail
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Missing credentials most likely:
smtp.Credentials = new System.Net.NetworkCredential("ideas#gmail.com", "password");
So:
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential("ideas#gmail.com", "Password");
smtp.EnableSsl = true;
smtp.Send(message);
Alternatively, you can store (almost all) this stuff in the app.config, though I'm not sure how secure you need it to be since the user/pass would be plainly visible to any user that opens the application's directory (and that file). For completion's sake:
<system.net>
<mailSettings>
<smtp from="ideas#gmail.com">
<network host="smtp.gmail.com"
enableSsl="true"
userName="ideas#gmail.com"
password="password"
port="587" />
</smtp>
</mailSettings>
</system.net>
Network credentials are very important, but sometimes we need to check if port 587 is blocked.
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("jorgesys#gmail.com", "whocaresdupe");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
} catch (Exception ex)
{
Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendEmail.aspx';}</script>");
}
My company blocks desktop/laptops from sending email using a setting in McAfee. Check the Windows Event view to see if there is an entry that an email was blocked.

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");

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.

sending email fails in C# 3.5

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

Categories

Resources