I try to move the SMTP setting from C# to XML. I stumbled in setting the network credential, see last line. What is the right syntax in XML for it?
using (var smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(md.From, "password");
await smtp.SendMailAsync(msg);
}
The SMTP old version setting in the web.config file:
<mailSettings>
<smtp from="From#gmail.com">
<network host="smtp.gmail.com" port="587" userName="From#gmail.com"
password="*******" enableSsl="true" />
</smtp>
</mailSettings>
Related
I wanted to send e-mail in my console application. I used:
SmtpClient client = new SmtpClient();
MailMessage msg = new MailMessage();
MailAddress to = new MailAddress("informatyka4445#wp.pl");
MailAddress from = new MailAddress("informatyka4444#wp.pl");
msg.IsBodyHtml = true;
msg.Subject = "Mail Title";
msg.To.Add(to);
msg.Body = "Your message";
msg.From = from;
try {
client.Send(msg);//THIS CAUSES ERROR
} catch (InvalidOperationException e) {
Console.WriteLine(e);
}
and it causes:
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
author of this code said that one should add:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.gmail.com" port="587" userName="your email address" password="your password" defaultCredentials="false" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
to Web.config but this is not ASP .NET MVC application and I don't see any web config.
You have to configure your SMTP client in code if you are not using any configuration file.
For example:
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = System.Net.NetworkCredential("youremail", "yourpassword");
smtp.EnableSsl = true;
i am tryiung to create a contact us page ,where the user clicks submit and sends an email to me, i looked at some examples, but they seem to be hard coding their email credentials into the code, i found out that for security m you can store the username and password in the webconfig file, below is my web config code and my default aspx.cs code, could anybody please help me solve the problem, this is the error i get
The remote name could not be resolved: 'smtp.gmail.com,587' Line 45: mailClient.Send(message);
Here is my appsettings and code:
<appSettings>
<add key="PFUserName" value="myemail#gmail.com"/>
<add key="PFPassWord" value="mypassword"/>
<add key="MailServerName" value="smtp.gmail.com,587"/>
</appSettings>
using System;
using System.Data;
using System.Configuration;
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.Mail;
using System.Web.Configuration;
using System.Net;
namespace WebApplication2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
SendMail(txtEmail.Text, txtComments.Text);
}
private void SendMail(string from, string body)
{
string Username = WebConfigurationManager.AppSettings["PFUserName"].ToString();
string Password = WebConfigurationManager.AppSettings["PFPassWord"].ToString();
string MailServer = WebConfigurationManager.AppSettings["MailServerName"].ToString();
NetworkCredential cred = new NetworkCredential(Username, Password);
string mailServerName = ("smtp.gmail.com,587");
MailMessage message = new MailMessage(from, Username, "feedback", body);
SmtpClient mailClient = new SmtpClient("smtp.gmail.com,587");
mailClient.EnableSsl = true;
mailClient.Host = mailServerName;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = cred;
mailClient.Send(message);
message.Dispose();
}
}
}
You need to set SMTP setting inside the mailSettings configuration in web.config like this
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="my#mail.com">
<network host="smtp.gmail.com" port="587" userName="myemail#gmail.com" password="mypassword" />
</smtp>
</mailSettings>
</system.net>
Your server name is smtp.gmail.com (remove the 587 from there). 587 is the port that smtp is using. So put this value in host property.
C# Code:
SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("sender#mail.com"));
mailMessage.Subject = "mailSubject";
mailMessage.Body = "mailBody";
smtpClient.Send(mailMessage);
This is what I currently use in my Web Config with some obvious edits
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="username#gmail.com">
<network defaultCredentials="false" host="smtp.gmail.com" port="587" userName=username" password="xxxxxxxxxxxx" />
</smtp>
</mailSettings>
</system.net>
in the CS file
using System.Net.Mail;
and
MailMessage myMessage = new MailMessage();
//subject line
myMessage.Subject = Your Subject;
//whats going to be in the body
myMessage.Body = Your Body Info;
//who the message is from
myMessage.From = (new MailAddress("Mail#Mail.com"));
//who the message is to
myMessage.To.Add(new MailAddress("Mail#Mail.com"));
//sends the message
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMessage);
for sending.
Your host name should be "smtp.gmail.com" and then set mailClient.Port to 587.
why did you dont compile in a class to make a dll?
Well, i use this code, enjoy :)
MailMessage mail = new MailMessage();
try
{
mail.To.Add(destinatario); // where will send
mail.From = new MailAddress("email that will send", "how the email will be displayed");
mail.Subject = "";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
// mail body
mail.Body = "email body";
// send email, dont change //
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("gmail account", "gmail pass"); // set 1 email of gmail and password
client.Port = 587; // gmail use this port
client.Host = "smtp.gmail.com"; //define the server that will send email
client.EnableSsl = true; //gmail work with Ssl
client.Send(mail);
mail.Dispose();
return true;
}
catch
{
mail.Dispose();
return false;
}
<configuration>
<!-- Add the email settings to the <system.net> element -->
<system.net>
<mailSettings>
<smtp>
<network
host="relayServerHostname"
port="portNumber"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>
...
</system.web>
</configuration>
above is web.config and here is back-end code :
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;
using System.Net.Configuration;
private void Email(string email, string pass, string customername)
{
SmtpSection smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
MailMessage mm = new MailMessage(smtp.Network.UserName,email);
mm.Subject = "Thank you for Registering with us";
mm.Body = string.Format("Dear {0},<br /><br />Thank you for Registering with <b> Us. </b><br /> Your UserID is <b>{1}</b> and Password is <b> {2} </b> <br /><br /><br /><br /><br /><b>Thanks, <br />The Ismara Team </b>", customername, email, pass);
mm.IsBodyHtml = true;
try
{
using (SmtpClient client = new SmtpClient())
{
client.Send(mm);
}
}
catch (Exception ex)
{
throw new Exception("Something went wrong while sending email !");
}
}
system will automatically get the details of smtp from web.config
i have a problem for sending email i enter valid email but when a i click submit button i get this error, Error: Failure sending mail
here is my code(web.Config)
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Soha#sohasys.com">
<!-- Default Port is [25] -->
<!-- Specific Port for Gmail is [587] NOT!!! [995]-->
<network defaultCredentials="false" host="mail.Sohasys.com" enableSsl="true" userName="Soha#sohasys.com" password="XXXX" port="587"/>
</smtp>
</mailSettings>
</system.net>
and this is my code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
try
{
System.Net.Mail.MailMessage oMailMessage = new System.Net.Mail.MailMessage();
oMailMessage.IsBodyHtml = true;
oMailMessage.Priority = System.Net.Mail.MailPriority.Normal;
oMailMessage.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.Never;
System.Net.Mail.MailAddress oMailAddress = null;
oMailAddress =
new System.Net.Mail.MailAddress(txtEmail0.Text, ttxtPhone.Text, System.Text.Encoding.UTF8);
oMailMessage.From = oMailAddress;
oMailMessage.Sender = oMailAddress;
oMailMessage.ReplyTo = oMailAddress;
oMailAddress =
new System.Net.Mail.MailAddress("Soha#sohasys.com", "", System.Text.Encoding.UTF8);
oMailMessage.To.Add(oMailAddress);
// oMailMessage.CC
// oMailMessage.Bcc
oMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
oMailMessage.Subject = "(From WebSite)" + " : " + txtUsername.Text;
oMailMessage.BodyEncoding = System.Text.Encoding.UTF8;
oMailMessage.Body = txtBody.Text;
System.Net.Mail.SmtpClient oSmtpClient = new System.Net.Mail.SmtpClient("Soha#sohasys.com", 587);
oSmtpClient.EnableSsl = true;
oSmtpClient.Timeout = 100000;
// oSmtpClient.UseDefaultCredentials = false;
// ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
oSmtpClient.Send(oMailMessage);
Label5.Visible = true;
Label5.Text = "Your Email Send SuccesFully.";
}
catch (System.Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
}
please insert this in web.config
system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="Soha#sohasys.com">
<!-- Default Port is [25] -->
<!-- Specific Port for Gmail is [587] NOT!!! [995]-->
<network defaultCredentials="false" host="mail.Sohasys.com" enableSsl="false" userName="Soha#sohasys.com" password="XXXX" port="587"/>
</smtp>
</mailSettings>
set enableSsl to false.
Its possible you have wrong settings.
pls try enableSsl="false"
try please instead of the host "mail.Sohasys.com" put the ip address of the smtp in the
web.config.
and why you mention gmail specific port ... if you use gmail smtp why you using
"mail.Sohasys.com" use google instead
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;
}
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);