Sending email with ASP.net - c#

So i've been searching stackoverflow for a way to send emails using a gmail account via a asp website...
I've tried many ways including Sending email in .NET through Gmail which seemed to be the best due to amount of upvotes he got.
However sadly it still doesn't work for me! I keep getting a time out.
Here's my code:
var fromaddress = new MailAddress("from#gmail.com", "from");
var toaddress = new MailAddress("to#address.com", "to");
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.EnableSsl = true;
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
}
catch (Exception ex)
{
return false;
}
in my web.config I have
<system.net>
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" port="587"/>
</smtp>
</mailSettings>
</system.net>
According to several sites i've visited this should work!!! .. but it doesn't.
Is there still anything i'm doing wrong?

You never set the login add this before your smtpClient.Send() Method.
NetworkCredential NetCrd = new NetworkCredential(youracc, yourpass);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = NetCrd;
Load the web.config via ConfigurationManager if it does not work automatically.

As suggested on this page, try installing telnet to see if you can connect to the mail server. It could be a firewall issue on your server. You can also try using another port as suggested in the link.

Your code seems fine to me.
Try to deliberately enter false credentials. If you get a different errormessage you are connected to gmail and there is a problem there.
If you get the same timeout problem, it is probably not a software thing but a firewall issue.
longshot - update
Perhaps there is a web.config issue? Try to specify everything in code like this. I have this working in real life with Gmail so if this does not work it definitely is a firewall/connection thing.
SmtpClient mailClient = new SmtpClient();
//This object stores the authentication values
System.Net.NetworkCredential basicCredential =
new System.Net.NetworkCredential("username#mydomain.com", "****");
mailClient.Host = "smtp.gmail.com";
mailClient.Port = 587;
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCredential;
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("info#mydomain.com", "Me myself and I ");
message.From = fromAddress;
//here you can set address
message.To.Add("to#you.com");
//here you can put your message details
mailClient.Send(message);
Good luck..

Can you try this out?
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromAddress"], ConfigurationManager.AppSettings["displayName"]); //Default from Address from config file
MailAddress toAddress = new MailAddress("abc#gmail.com", "from sender");
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = ConfigurationManager.AppSettings["smtpClientHost"];
//Default port will be 25
smtpClient.Port = int.Parse(ConfigurationManager.AppSettings["portNumber"]); //From config file
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(toAddress);
message.Subject = ConfigurationManager.AppSettings["Subject"]; //Subject from config file
message.IsBodyHtml = false;
message.Body = "Hello World";
smtp.DeliveryMethod = SmtpDeliveryMethod.NetWork
smtpClient.Send(message);
}
catch (Exception ex)
{
throw ex.ToString();
}
The configuration settings would be,
<configuration>
<appSettings>
<add key="smtpClientHost" value="mail.localhost.com"/> //SMTP Client host name
<add key="portNumber" value="25"/>
<add key="fromAddress" value="defaultSender#gmail.com"/>
<add key="displayName" value="Auto mail"/>
<add key="Subject" value="Auto mail Test"/>
</appSettings>
</configuration>

Put these settings EnableSSL = true and defaultCredentials="false" in your web.config settings. Gmail smtp server requires SSL set to true and mailclient.UseDefaultCredentials = false should be false if you are providing your credentials.
Update Web.Config Settings:
<mailSettings>
<smtp from="from#gmail.com" deliveryMethod="Network">
<network userName="from#gmail.com" password="mypassword" host="smtp.gmail.com" defaultCredentials="false" port="587" enableSsl="true"/>
</smtp>
</mailSettings>
And check this shorter code to send mail after providing settings in the web.config. even it send email much fast rather then specifying setting while creating the smtpclient setting in the mail sending function.
Public void SendEmail(string toEmailAddress, string mailBody)
{
try
{
MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.To.Add(toEmailAddress);
mailMessage.Subject = "Mail Subjectxxxx";
mailMessage.Body = mailBody;
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
return "Mail send successfully";
}
catch (SmtpException ex)
{
return "Mail send failed:" + ex.Message;
}
Working very much fine at my side..

var smtpClient = new SmtpClient(gmailSmtpServer, gmailSmtpPort)
{
Credentials = new NetworkCredential(FromGEmailAddress, FromGEmailAddressPassword),
EnableSsl = true
};
try
{
using (var message = new MailMessage(fromaddress, toaddress))
{
message.Subject = "Test";
message.Body = "Testing this shit!";
smtpClient.Send(message);
return true;
}
}
catch (Exception exc)
{
// error
return false;
}

Related

Unable to send emails using C# code from GoDaddy configured Office 365 account

I have purchased "Office 365 Email Essentials" plan from GoDaddy for sending the emails. I am able to send and receive these emails in my outlook mailbox, but not programatically via C# code.
I keep receiving the error "
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.7.57 SMTP; Client was not
authenticated to send anonymous mail during MAIL FROM
[BMXPR01CA0092.INDPRD01.PROD.OUTLOOK.COM]"
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("xxx#gmail.com", "xxx"));
msg.From = new MailAddress("xxx#mydomain.com", "Admin");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxx#mydomain.com", "mypassword","mydomain.com");
client.Port = 587;
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
//Send the msg
try
{
client.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
And here is the mailsettings entry in the config file -
<mailSettings>
<smtp from="xxx#mydomain.com">
<network host="smtp.office365.com" port="587" />
</smtp>
</mailSettings>
The settings I see in the Outlook are -
Server name: smtp.office365.com
Port: 587
Encryption method: STARTTLS
Alternatively, I also tried using the userid in place of actual email address in the network credentials,but that did not work either.
I also tried to use the MX Txt record in GoDaddy i.e. server "relay-hosting.secureserver.net" and port #25 ,but no luck.
I also changed the settings in "Mailbox delegation" as per the link http://edudotnet.blogspot.com/2014/02/smtp-microsoft-office-365-net-smtp.html , but that did not help either.
Please help me what am I missing in these steps.
After spending hours on this, I have found that the smtp host for the godaddy configured office 365 mail id is "smtpout.secureserver.net".
Also program the client as closed connection like below:
SmtpClient client = new SmtpClient {
Host = "smtpout.secureserver.net",
Credentials = new NetworkCredential("USERNAME#DOMAIN.COM", "YOURPWD"),
Port = 587,
EnableSsl = true,
Timeout = 10000
};
after these updates, it will work!!! Enjoy!
Example Console application code!
static void Main(string[] args)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string userId = "username#domainname.com";
string _pwd = "mypassword";
var toAddress = "touseremailaddress";
SmtpClient client = new SmtpClient
{
Host = "smtpout.secureserver.net",
Credentials = new NetworkCredential(userId, _pwd),
Port = 587,
EnableSsl = true
};
var Msg = new MailMessage();
Msg.From = new MailAddress(userId);
Msg.To.Add(new MailAddress(toAddress.ToString()));
Msg.Subject = "TEST EMAIL";
Msg.Body = "Hello world";
Console.WriteLine("start to send email over SSL...");
client.Send(Msg);
Console.WriteLine("email was sent successfully!");
Console.ReadLine();
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
Console.ReadLine();
}
}
Try to change the SMTP server name to outlook.office365.com instead of smtp.office365.com

An error while using a local SMTP pickup directory

I am configuring SMTPClient with these codes to use local directory:
EmailHelper.cs
public bool SendMail(string from, string to, string cc, string subject, string body, bool isBodyHtml)
{
try
{
var smtpClient = new SmtpClient();
string pickUpFolder = #"C:\Users\kerem\Documents\Visual Studio 2012\Projects\Blog\Blog\Email";
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
pickUpFolder = mailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
smtpClient.PickupDirectoryLocation = pickUpFolder;
}
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(new MailAddress(to));
if (cc != "")
mailMessage.CC.Add(new MailAddress(cc));
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
return true;
}
catch (Exception err)
{
return false;
}
}
EmailHelper.cs in BlogServices Project in my Blog solution. Also there is a Blog Project in the same solution. I have replaced Blog\Blog\Email in pickUpFolder with Blog\Email and Blog\BlogServices\Email but I still have an error of Only absolute directories are allowed for pickup directory. Where is my mistake? Thanks in advance.
Add this to your project's web.config.
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\Users\kerem\Documents\Visual Studio 2012\Projects\Blog\Blog\Email\"/>
</smtp>
</mailSettings>
</system.net>
Alternatively, try deleting this line: pickUpFolder = mailSettings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;, but I suspect you'll have other problems if you go that route.

how to send mail by using smtp in asp.net

i need solution for this error
i am run that time some error occur there is:Send Email Failed.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. i1sm8651517pbj.70
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
#region "Send email"
protected void btnSendmail_Click(object sender, EventArgs e)
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress(txtEmail.Text, txtName.Text);
// You can specify the host name or ipaddress of your server
// Default in IIS will be localhost
smtpClient.Host = "smtp.gmail.com";
//Default port will be 25
smtpClient.Port = 587;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add("muthu17green#gmail.com");
message.Subject = "Feedback";
// CC and BCC optional
// MailAddressCollection class is used to send the email to various users
// You can specify Address as new MailAddress("admin1#yoursite.com")
message.CC.Add("muthu17green#gmail.com");
message.CC.Add("muthu17green#gmail.com");
// You can specify Address directly as string
message.Bcc.Add(new MailAddress("muthu17green#gmail.com"));
message.Bcc.Add(new MailAddress("muthu17green#gmail.com"));
//Body can be Html or text format
//Specify true if it is html message
message.IsBodyHtml = false;
// Message body content
message.Body = txtMessage.Text;
// Send SMTP mail
smtpClient.Send(message);
lblStatus.Text = "Email successfully sent.";
}
catch (Exception ex)
{
lblStatus.Text = "Send Email Failed.<br>" + ex.Message;
}
}
#endregion
#region "Reset"
protected void btnReset_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtMessage.Text = "";
txtEmail.Text = "";
}
#endregion
}
You need to set the SmtpClient.Credentials property:
smtpClient.Credentials = new NetworkCredentials("yourUserName", "yourPassword");
This is what is used to authenticate in order to send the message. You may also need to ensure that SSL is enabled:
smtpClient.EnableSsl = true;
SmtpClient.Credentials Property MSDN Reference
It seems that you are trying to send an email using GMail, which requires SSL.
See this Google reference post.
So in your web.config, enable SSL this way:
<system.net>
<mailSettings>
<smtp deliveryMethod="network">
<network host="smtp.gmail.com" port="587" enableSsl="true" userName="YOURUSERNAME" password="YOURPASSWORD" />
</smtp>
</mailSettings>
</system.net>
Alternatively, you can set it programmatically this way:
smtpClient.EnableSsl = true;
I think you forgot to set EnableSSL property to true which is required for gmail.
Here is the sample code:
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(txtFrom.Text);
msg.To.Add(new MailAddress(txtTo.Text));
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpClient mySmtpClient = new SmtpClient();
System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential(txtFrom.Text,txtPwd.Text);
mySmtpClient.Host = "smtp.gmail.com";
mySmtpClient.Port=587;
mySmtpClient.EnableSsl = true;
mySmtpClient.UseDefaultCredentials = false;
mySmtpClient.Credentials = myCredential;
mySmtpClient.Send(msg);
msg.Dispose();
lberr.Text="Message sent successfully";
clrtxt();
}
catch(SmtpException)
{
lberr.Text="SMTP Error handled";
}
}
public void SendMail()
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(MailTo.Text);
mail.From = new MailAddress(MailFrom.Text,"Invoice");
mail.Subject = Subject.Text;
mail.Body = Body.Text;
mail.IsBodyHtml = true;
string FileName = Path.GetFileName(FileUploadAttachments.PostedFile.FileName);
Attachment attachment = new Attachment(FileUploadAttachments.PostedFile.InputStream ,FileName);
mail.Attachments.Add(attachment);
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("Your_Email#Email.com", "Your_Email_Password");
client.Host = "smtpout.secureserver.net";
client.Port = 80;
try
{
client.Send(mail);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}

Cannot get IIS pickup directory (From Windows Service)

I am facing the above-mentioned error while sending emails from windows service. Your suggestion is much appreciated.
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMsg = this.ComposeMailMessage();
smtpClient.Send(mailMsg);
Configuration
<system.net>
<mailSettings>
<smtp from="user1#mycompany.com" deliveryMethod="Network">
<network host="smtpsvr.mycompany.com" port="25" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
Maybe mine is not the answer you're searching, but try this (avoiding IIS):
try
{
// To
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add(to_Address);
// From
MailAddress mailAddress = new MailAddress(from_address);
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = subject;
mailMsg.Body = body;
// Init SmtpClient and send
SmtpClient smtpClient = new SmtpClient(smtp_server, port);
// System.Net.NetworkCredential credentials =
// new System.Net.NetworkCredential(smtp_user, smtp_pwd);
// smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine( ex.Message );
}
You probably need to set the SmtpClient PickupDirectory manually.
There is an example of how to do that in the Lukas Pokorny's answer:
Cannot get IIS pickup directory
Try add the following line to your program. This line needs the IIS Admin and SMTP service running on your desktop.
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
So it will become like this
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMsg = this.ComposeMailMessage();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Send(mailMsg);

send email from asp.net app

i configure all setting for send email using c# but when i execute than i get the following error
The requested address is not valid in its context 74.125.53.109:25
my code is
MailMessage mail = new MailMessage();
mail.To.Add("to#gmail.com");
mail.From = new MailAddress("from#gmail.com");
mail.Subject = "Test Email";
string Body = "<b>Welcome to CodeDigest.Com!!</b>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["SMTP"];
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]);
smtp.EnableSsl = true;
smtp.Send(mail);
Web.Config
<appSettings>
<add key="SMTP" value="smtp.gmail.com"/>
<add key="FROMEMAIL" value="mail#gmail.com"/>
<add key="FROMPWD" value="password"/>
</appSettings>
Sending email in .NET through Gmail
This link have a full code of sending email and its proper working
sending email by gmailin my pc.
I figure I'll just post the combined effort of posts here:
Add this to your configuration file, changing the email/username/password. You may have to change the port based on what Brian Rogers posted.
<system.net>
<mailSettings>
<smtp from="some.user#gmail.com" deliveryMethod="Network">
<network host="smtp.gmail.com" port="587" enableSsl="true" userName="some.user#gmail.com" password="mypassword"/>
</smtp>
</mailSettings>
</system.net>
Use this in your code
MailMessage mail = new MailMessage();
mail.To.Add("to#gmail.com");
mail.From = new MailAddress("from#gmail.com");
mail.Subject = "Test Email";
string Body = "<b>Welcome to CodeDigest.Com!!</b>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
Port 25 is the default port but not the correct port for sending email over SSL. Since you are using SSL, you will need to set smtp.Port = 465, according to Google's help page on the topic: http://support.google.com/mail/bin/answer.py?hl=en&answer=13287
I think the address is not valid because it targets port 25 in the context of an SSL connection.
I did this already and I have already tested it out in Gmail.
StackOverflow - Send email with attachments
Gmail port = 465
Use SSL = true
You cant specify port 25 with :25 after the IP.
It will default to port 25 so you don't need it. If you want to change the port use the following:
mail.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"portnumber"
);
This is the function which works well for send mail, i had checked it and it's working.
private static bool testsendemail(MailMessage message)
{
try
{
MailMessage message1 = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
MailAddress fromAddress = new MailAddress("FromMail#Test.com");
message1.From = fromAddress;
message1.To.Add("ToMail#Test1.com");
message1.Subject = "This is Test mail";
message1.IsBodyHtml = true;
message1.Body ="You can write your body here" + message;
// We use yahoo as our smtp client
smtpClient.Host = "smtp.mail.yahoo.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(
"SenderMail#yahoo.com",
"YourPassword"
);
smtpClient.Send(message1);
}
catch
{
return false;
}
return true;
}
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void btnSend_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("xxx#yourdomain.com");
msg.To.Add(txtTo.Text); //Text Box for To Address
msg.Subject = txtSubject.Text; //Text Box for subject
msg.IsBodyHtml = true;
msg.Body = txtBody.Text; //Text Box for body
msg.Priority = MailPriority.High;
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(
"relay-hosting.secureserver.net",
25
);
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(
"xxx#yourdomain.com",
"yourpassword"
);
client.Host = "relay-hosting.secureserver.net";
client.EnableSsl = false;
object userstate = msg;
client.Send(msg);
}
}

Categories