correct code for sending an email, asp.net - c#

I have a form that allows a user to send an email to everyone on a mailing list (linq table). I'm having trouble with the correct code and syntax for linking to the smtp server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Web.Security;
using System.Web.Mail;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
public partial class MassEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
mailingListClassDataContext Class = new mailingListClassDataContext();
var emaillist = from emails in Class.mailinglistMembers select emails.email;
foreach (var subcriber in emaillist)
{
MailMessage objMail = new MailMessage();
objMail.From = "test#test.com";
objMail.To = subcriber;
objMail.BodyFormat = MailFormat.Html ;
//The subject of the message
objMail.Subject = "test email that i hope works" ;
//he message text
objMail.Body = Editor1.Content;
//need help in this area
SmtpClient client = new SmtpClient();
SmtpClient.Send(objMail);
}
}
}

The best solution is to put the smtp server details in your web.config
<system.net>
<mailSettings>
<smtp>
<network
host="smtp.emailhost.com"
port="25"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>

using (var db = new mailingListClassDataContext())
{
var client = new System.Net.Mail.SmtpClient();
var recipients = from e in db.mailinglistMembers
select e.email;
foreach (string recipient in recipients)
{
var message = new System.Net.Mail.MailMessage("sender#example.com", recipient);
message.Subject = "Hello World!";
message.Body = "<h1>Foo bar</h1>";
message.IsBodyHtml = true;
client.Send(message);
}
}
Try setting up configuration in your web.config or machine.config. Make sure you've specified the correct address and port of the SMTP server.
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network" from="me#example.com">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>

You can pass the SMTP server IP or name in the constructor to SmtpClient or set it explicity through the Host property.

You probably want to set the Host (and possibly the Credentials) property on the SmptClient. The server (host) defaults to localhost.
Also consider creating the client instance outside of the loop.

Related

How to Pass App Settings to Mail Method in C#

I'm trying to pass the App Settings keys listed into the Send Email function so they can be customized by the user, but for some reason I can't get it to work. I've been testing with the "Body" key to see if I can even get 1 to work.
App Config File
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="MailHost" value="smtp.gmail.com" />
<add key="PortNumber" value="587" />
<add key="MailPassword" value="**********" />
<add key="Recipient" value="*************appspotmail.com" />
<add key="Body" value="Sent from WOX Mail Plugin." />
<add key="MailUser" value="**********#gmail.com" />
</appSettings>
</configuration>
Main.CS File
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wox.Plugin;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace Wox.Plugin.Version1
{
public class Main :IPlugin
{
public void Init(PluginInitContext context)
{
}
public List<Result> Query(Wox.Plugin.Query query)
{
var subject = query.Search;
string emailbody = ConfigurationManager.AppSettings.Get("Body");
return new List<Result>()
{
new Result()
{
Title = string.Format("Add: {0}", subject),
IcoPath = "Images\\icon.png",
SubTitle = "Send New Task to Marvin",
Action = (Func<ActionContext, bool>) (c =>
{
Main.SendEmail(subject, emailbody);
return true;
})
}
};
}
public static void SendEmail(string inputsubject, string body)
{
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("****************");
message.To.Add("********************8");
message.Subject = inputsubject;
message.Body = body;
message.IsBodyHtml = false;
using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.Credentials = (ICredentialsByHost)new NetworkCredential("*************", "************");
smtpClient.EnableSsl = true;
smtpClient.Send(message);
}
}
}
}
}
It feels like I've tried placing the ConfigurationManager line in every perceivable spot to make it happen, and nothing has worked. The subject goes through fine, but not the body.
The email always sends successfully, but the information in the body doesn't send. I've also tried appending it to the subject line, but it doesn't show up there either.

Error with changing SMTP Settings to use Config rather than setting it up in .cs

Currently my WPF application has the SMTP set up as followed:
string MailTo = txtBoxEmail.Text;
string MailFrom = "datfakeemaildoe#gmail.com ";
string Subject = "Cool Subject";
string Password = "*******";
SmtpClient smtpmail = new SmtpClient();
smtpmail.Host = "smtp.gmail.com";
smtpmail.Port = 587;
smtpmail.EnableSsl = true;
smtpmail.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpmail.UseDefaultCredentials = false;
smtpmail.Credentials = new NetworkCredential(MailFrom, Password);
MailMessage message = new MailMessage(MailFrom, MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
However, I'd like to manage all of this in the config rather than the .cs if possible.
Currently, I set up my App.Config as followed:
<configuration>
<appSettings>
<add key="host" value="smtp.gmail.com" />
<add key="port" value="587" />
<add key="MailFrom" value="datfakeemaildoe#gmail.com" />
<add key="Password" value="*******" />
</appSettings>
</configuration>
Problem is, how to I implement it properly now in the .cs
I tried this:
using System.Configuration;
using System.Net.Configuration;
using System.Net;
using System.Net.Mail;
...
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
...
string MessageTosend = #"there is html in here, trust me";
MailAddress Sender = new MailAddress(ConfigurationManager.AppSettings["MailFrom"]);
string MailTo = txtBoxEmail.Text;
string Subject = "Cool Subject";
SmtpClient smtp = new SmtpClient()
{
host = ConfigurationManager.AppSettings["host"],
port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network;
UseDefaultCredentials = false;
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["Password"])
};
MailMessage message = new MailMessage(ConfigurationManager.AppSettings["MailFrom, MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
...
BUT ConfigurationManager is generating an error that says does not exist in the current context, even though I have...
using System.Configuration;
using System.Net.Configuration;
using System.Net;
using System.Net.Mail;
...already. I just want to be able to change SMTP settings in the config rather than having to update the code behind for my application in case things change later.
Not sure if I'm doing it wrong or if I'm just missing something entirely. I referenced this to know how to use the app.config.
As stated on Scott Gu's blog, there's already a section in .config specifically for these settings, no need to do it in App Settings. The .NET framework automatically reads these settings in without the need to write C# to do it. Here's the MSDN documentation.
Example:
<system.net>
<mailSettings>
<smtp from="test#foo.com">
<network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
No need to specify any code for loading of the configuration.
Figured out the ConfigurationManager problem.
While <system.net><mailSettings> ... works, so does my original <appSettings>. The reason why ConfigurationManager was running into a issue was because System.Configuration.dll was missing in my references (source)
Adding this, I was able to call the keys I added in my App.config
Then I changed the way it was used in the .cs
SmtpClient smtpmail = new SmtpClient();
smtpmail.Host = ConfigurationManager.AppSettings["host"];
smtpmail.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
smtpmail.EnableSsl = true;
smtpmail.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpmail.UseDefaultCredentials = false;
smtpmail.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["Password"]);
MailMessage message = new MailMessage(ConfigurationManager.AppSettings["MailFrom"], MailTo, Subject, MessageTosend);
message.IsBodyHtml = true;
Worked like a charm. :)

Sending mail Using C# asp.net [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
send email asp.net c#
I have sent mail several times using the technique several times before but somehow it doesnt work i am providing the code in the following:
MailMessage myMailMessage = new MailMessage();
myMailMessage.Subject = "Response From Client";
myMailMessage.Body = "hello word";
myMailMessage.From = new MailAddress("mymail#gmail.com", "jub");
myMailMessage.To.Add(new MailAddress("mymail#gmail.com", "Softden"));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(myMailMessage);
and my web.config is:
<mailSettings>
<smtp deliveryMethod = "Network" from="Jubair <mymail#gmail.com>">
<network defaultCredentials="false" enableSsl="true" userName="mymail#gmail.com" password="Mypassword" host="smtp.gmail.com" port="587"></network>
</smtp>
</mailSettings>
it says the smtp server requires a secure connection or the client was not authenticated.. Please help
Try adding something like this
Per Dominic's answer on Stackoverflow look at he following example
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
//UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
//----------------- A simple approach below ---------------
I just tested this below and it works
var mail = new MailMessage();
// Set the to and from addresses.
// The from address must be your GMail account
mail.From = new MailAddress("noreplyXYZ#gmail.com");
mail.To.Add(new MailAddress(to));
// Define the message
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = message;
// Create a new Smpt Client using Google's servers
var mailclient = new SmtpClient();
mailclient.Host = "smtp.gmail.com";//ForGmail
mailclient.Port = 587; //ForGmail
// This is the critical part, you must enable SSL
mailclient.EnableSsl = true;//ForGmail
//mailclient.EnableSsl = false;
mailclient.UseDefaultCredentials = true;
// Specify your authentication details
mailclient.Credentials = new System.Net.NetworkCredential("fromAddress#gmail.com", "xxxx123");//ForGmail
mailclient.Send(mail);
mailclient.Dispose();
//The .config settings there are two options on how you could set this up I am suspecting that this is the issue you are having
<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>
or option 2
<configuration>
<appSettings>
<add key="smtpClientHost" value="mail.localhost.com"/> //SMTP Client host name
<add key="portNumber" value="587"/>
<add key="fromAddress" value="yourEmailAddress#gmail.com"/>
</appSettings>
</configuration>
Send Email from Yahoo, Gmail, Hotmail (C#)
http://www.codeproject.com/Tips/520998/Send-Email-from-Yahoo-Gmail-Hotmail-Csharp
These are evry good tutorials with samples. make your demo email id. pass your id and its password as parameters. and send mail to anyone.
http://www.codeproject.com/Articles/15807/Easy-SMTP-Mail-Using-ASP-NET-2-0
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
http://www.codeproject.com/Tips/490604/Sending-mail-using-ASP-NET-with-optional-parameter
if you are still unable to send email make sure to change the port number. but 587 should work normally.
Make sure you contact the email server side to see what kind of authentication they accept to relay.

How to read system.net/mailSettings/smtp from Web.config

This is my web.config mail settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="smthg#smthg.net">
<network defaultCredentials="true" host="localhost" port="587" userName="smthg#smthg.net" password="123456"/>
</smtp>
</mailSettings>
</system.net>
and here's how I try to read the values from web.config
var smtp = new System.Net.Mail.SmtpClient();
var credential = new System.Net.Configuration.SmtpSection().Network;
string strHost = smtp.Host;
int port = smtp.Port;
string strUserName = credential.UserName;
string strFromPass = credential.Password;
But credentials are always null. How can i access these values?
Since no answer has been accepted, and none of the others worked for me:
using System.Configuration;
using System.Net.Configuration;
// snip...
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string username = smtpSection.Network.UserName;
It is not necessary to use the ConfigurationManagerand get the values manually. Simply instantiating an SmtpClient is sufficient.
SmtpClient client = new SmtpClient();
This is what MSDN says:
This constructor initializes the Host, Credentials, and Port properties for the new SmtpClient by using the settings in the application or machine configuration files.
Scott Guthrie wrote a small post on that some time ago.
By using the configuration, the following line:
var smtp = new System.Net.Mail.SmtpClient();
Will use the configured values - you don't need to access and assign them again.
As for the null values - you are trying accessing the configuration values incorrectly. You are just creating an empty SmtpSection instead of reading it from configuration.
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("<the section name>");
var credentials == smtpSection.Network;
I think if you have defaultCredentials="true" set you will have the credentials = null as you are not using them.
Does the email Send when you call the .Send method?
So
This is my web config mail settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="smthg#smthg.net">
<network defaultCredentials="false" host="localhost" port="587"
userName="smthg#smthg.net" password="123456"/>
</smtp>
</mailSettings>
</system.net>
and this is cs
SmtpClient smtpClient = new SmtpClient();
string smtpDetails =
#"
DeliveryMethod = {0},
Host = {1},
PickupDirectoryLocation = {2},
Port = {3},
TargetName = {4},
UseDefaultCredentials = {5}";
Console.WriteLine(smtpDetails,
smtpClient.DeliveryMethod.ToString(),
smtpClient.Host,
smtpClient.PickupDirectoryLocation == null
? "Not Set"
: smtpClient.PickupDirectoryLocation.ToString(),
smtpClient.Port,
smtpClient.TargetName,
smtpClient.UseDefaultCredentials.ToString)
);
//You can access the network credentials in the following way.
//Read the SmtpClient section from the config file
var smtp = new System.Net.Mail.SmtpClient();
//Cast the newtwork credentials in to the NetworkCredential class and use it .
var credential = (System.Net.NetworkCredential)smtp.Credentials;
string strHost = smtp.Host;
int port = smtp.Port;
string strUserName = credential.UserName;
string strFromPass = credential.Password;
make sure you have reference to System.Net in your application
Set defaultCredentials="false", because when it's set to true, no credentials are used.

Email sending error in ASP.NET using C#

This is the code for email sending, but it gives error in try block:
protected void Page_Load(object sender, EventArgs e)
{
EmailUtility email = new EmailUtility();
email.Email = new MailMessage();
string body = email.GetEmailTemplate(Server.MapPath("~/EmailTemplates"), "test.htm");
EmailMessageToken token = new EmailMessageToken();
token.TokenName = "$Name$";
token.TokenValue = "Ricky";
EmailMessageTokens tokens = new EmailMessageTokens();
tokens.Add(token);
//av.LinkedResources.Add(lr);
email.Email.Body = email.ReplaceTokens(body, tokens);
email.Email.To.Add(new MailAddress("sahil4659#gmail.com"));
email.Email.IsBodyHtml = true;
email.Email.From = new MailAddress("sahil4659#gmail.com");
email.Email.Subject = "Hello from bootcamp";
email.SMTP.Host = ConfigurationManager.AppSettings["SMTPServer"];
try
{
email.SMTP.Send(email.Email);
Response.Write("Email sent !");
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
The error is:
at System.Net.Mail.IisPickupDirectory.GetPickupDirectory()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at _Default.Page_Load(Object sender, EventArgs e) in c:\Users\Sahil\Desktop\Csharp Email Code(2)\Test website\EmailTest.aspx.cs:line 38
I'm going to read your mind and assume that you're seeing System.Net.Mail.SmtpException: Cannot get IIS pickup directory. Googling around, I see references to SMTP configuration you'll need in your web configuration. Your mail server may require credentials, so you might need something like this:
<system.net>
<mailSettings>
<smtp from="fromaddress">
<network defaultCredentials="true"
host="smtpservername" port="smtpserverport"
userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
... in your web.config. Essentially, configure your web app to be able to talk with the SMTP server.
See this thread for more reference, and here's relevant MSDN documentation.

Categories