Knowledgebase: ASP .NET / ASP
System.Web.Mail Sample C# and VB .NET Script
Posted by Arvand Sabetian (Import) on 14 May 2010 07:53 AM
|
|
The following scripts use SMTP Authentication to send mail from your script - C#: <% @Page Language="C#" %> <% @Import Namespace="System.Web.Mail" %> <% MailMessage mail = new MailMessage(); mail.To = "[email protected]"; mail.From = "[email protected]"; mail.Subject = "this is a test email."; mail.Body = "Some text goes here"; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "[email protected]"); //set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "PASSWORD"); //set your password here SmtpMail.SmtpServer = "localhost"; //your real server goes here SmtpMail.Send( mail ); %> VB .NET: <% @Page Language="VB" %> <% @Import Namespace="System.Web.Mail" %> <% Dim mail As New MailMessage() mail.To = "[email protected]" mail.From = "[email protected]" mail.Subject = "this is a test email." mail.Body = "Some text goes here" mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1") 'basic authentication mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "[email protected]") 'set your username here mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "PASSWORD") 'set your password here SmtpMail.SmtpServer = "localhost" 'your real server goes here SmtpMail.Send(mail) %> Reference: http://www.systemwebmail.com/faq/3.8.aspx | |
|
Comments (30)
Roger Martin
01 June 2010 09:06 AM
This code sample uses System.Web.Mail, which was deprecated when .NET 2.0 was released. See http://msdn.microsoft.com/en-us/library/system.web.mail.aspx. Please update using the recommended namespace System.Net.Mail. Thanks!
RESPONSE: Yes, you may wish to use system.net.mail if you wish. The link should be included on the Microsoft page we are referencing -
http://www.systemnetmail.com/faq/4.2.aspx
This KB is here to provide a quick reference as to what type of code should be used as there are many different ways to send mail through our servers.
RESPONSE: Yes, you may wish to use system.net.mail if you wish. The link should be included on the Microsoft page we are referencing -
http://www.systemnetmail.com/faq/4.2.aspx
This KB is here to provide a quick reference as to what type of code should be used as there are many different ways to send mail through our servers.
Llewellyn Preece
09 November 2010 07:26 AM
-- since I just had to put this together, thought I'd offer up a simple copy/paste helper to save someone some time. I agree with Roger that we ought to use the system.net mail goodies. HTH. LP
public static void CreateAndSendEmailMessage()
{
string to = "EMAIL ADDRESS BEING SENT TO - CAN ALSO BE A COLLECTION OF ADDRESSES";
string from = "EMAIL ADDRESS FROM";
string subject = "EMAIL SUBJECT GOES HERE";
string body = @"EMAIL BODY GOES HERE";
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
message.Priority = System.Net.Mail.MailPriority.Normal;
//THIS NEXT FOUR LINES ARE IN CASE YOU NEED MORE CONTROL OVER SPECIFICS AND CANNOT USE THE web.config FILE OPTION
//PASSWORD SHOULD BE SEEN AS A SECURITY RISK SO USING ENCRIPTION WOULD BE IDEAL - THESE ARE ALL HANDLED BY web.config INCLUDING THE client.Credentials LINE. SWEET STUFF IMHO.
//System.Net.NetworkCredential netwrkCrd = new System.Net.NetworkCredential();
//netwrkCrd.UserName = "VALID ARVIXE EMAIL USER NAME";
//netwrkCrd.Password = "VALID ARVIXE EMAIL USER NAME'S PASSWORD";
//client.Credentials = netwrkCrd;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateAndSendEmailMessage(): {0}", ex.ToString());
}
}
===============NEAT WAY TO MANAGE EMAIL - ALSO ALLOWS FOR TIGHTER SECURITY ==============
<configuration>
<system.net>
<mailSettings>
<smtp from="DEFAULT EMAIL FROM - CAN BE OVERWRITTEN IN THE FUNCTION">
<network host="SMTP SERVER NAME" port="25 or 26 - SEE ARVIXE DOCS ON THIS" userName="USER EMAIL ADDRESS BEING USED TO LOG ONTO SMTP SERVER" password="PASSWORD FOR SAME"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
public static void CreateAndSendEmailMessage()
{
string to = "EMAIL ADDRESS BEING SENT TO - CAN ALSO BE A COLLECTION OF ADDRESSES";
string from = "EMAIL ADDRESS FROM";
string subject = "EMAIL SUBJECT GOES HERE";
string body = @"EMAIL BODY GOES HERE";
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body);
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
message.Priority = System.Net.Mail.MailPriority.Normal;
//THIS NEXT FOUR LINES ARE IN CASE YOU NEED MORE CONTROL OVER SPECIFICS AND CANNOT USE THE web.config FILE OPTION
//PASSWORD SHOULD BE SEEN AS A SECURITY RISK SO USING ENCRIPTION WOULD BE IDEAL - THESE ARE ALL HANDLED BY web.config INCLUDING THE client.Credentials LINE. SWEET STUFF IMHO.
//System.Net.NetworkCredential netwrkCrd = new System.Net.NetworkCredential();
//netwrkCrd.UserName = "VALID ARVIXE EMAIL USER NAME";
//netwrkCrd.Password = "VALID ARVIXE EMAIL USER NAME'S PASSWORD";
//client.Credentials = netwrkCrd;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateAndSendEmailMessage(): {0}", ex.ToString());
}
}
===============NEAT WAY TO MANAGE EMAIL - ALSO ALLOWS FOR TIGHTER SECURITY ==============
<configuration>
<system.net>
<mailSettings>
<smtp from="DEFAULT EMAIL FROM - CAN BE OVERWRITTEN IN THE FUNCTION">
<network host="SMTP SERVER NAME" port="25 or 26 - SEE ARVIXE DOCS ON THIS" userName="USER EMAIL ADDRESS BEING USED TO LOG ONTO SMTP SERVER" password="PASSWORD FOR SAME"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
kiran
11 May 2011 11:49 PM
hiLlewellyn,
thx for the example , but where i can write smtp details and port address if i m not going to use web.config settings
thx for the example , but where i can write smtp details and port address if i m not going to use web.config settings
Arvand Sabetian
02 June 2011 11:25 PM
Its outlined in his code commented -
//System.Net.NetworkCredential netwrkCrd = new System.Net.NetworkCredential();
//netwrkCrd.UserName = "VALID ARVIXE EMAIL USER NAME";
//netwrkCrd.Password = "VALID ARVIXE EMAIL USER NAME'S PASSWORD";
//client.Credentials = netwrkCrd;
You would need to remove the // characters.
//System.Net.NetworkCredential netwrkCrd = new System.Net.NetworkCredential();
//netwrkCrd.UserName = "VALID ARVIXE EMAIL USER NAME";
//netwrkCrd.Password = "VALID ARVIXE EMAIL USER NAME'S PASSWORD";
//client.Credentials = netwrkCrd;
You would need to remove the // characters.
Partheepan Ramalingam
14 May 2013 07:09 AM
Hi Arvand,
I am working for Techdata client and creating an application in which I need to send a mail if a user clicks forget password link in my application. Our company's applications are hosted in ARVIXE. I have checked the sample mail sending code in the Arvixe support community and found that "localhost" is been used as host for the SMTP Server. But this is not working. I am getting an error message as "The SMTP server requires a secure connection or the client was not authenticated. The server response was : SMTP authentication is required.". Please help me
I am working for Techdata client and creating an application in which I need to send a mail if a user clicks forget password link in my application. Our company's applications are hosted in ARVIXE. I have checked the sample mail sending code in the Arvixe support community and found that "localhost" is been used as host for the SMTP Server. But this is not working. I am getting an error message as "The SMTP server requires a secure connection or the client was not authenticated. The server response was : SMTP authentication is required.". Please help me
Michael Carr
16 May 2013 12:33 PM
If you can open a support ticket we will be glad to take a look. It sounds like your SMTP session is not logging in correctly. Make sure you are using a valid full email address as the login along with its associated password.
Joel Delpay
23 March 2015 12:14 PM
What is the smtpClient address?
Ryan C
31 March 2015 11:06 PM
This would be mail.yourdomain.com
naman nassar
21 April 2012 08:58 AM
here is the code that will work for sure.
C#
-----------
using System.Net.Mail;
MailMessage EmailMsg = new MailMessage();
EmailMsg.From = new MailAddress("[email protected]");
EmailMsg.To.Add(new MailAddress("[email protected]"));
EmailMsg.Subject = "Customer_Questions";
EmailMsg.Body = "your Customers body";
EmailMsg.IsBodyHtml = true;
EmailMsg.Priority = MailPriority.Normal;
EmailMsg.BodyEncoding = Encoding.UTF8;
SmtpClient MailClient = new SmtpClient("mail.namannassar.com", 25);
MailClient.UseDefaultCredentials = false;
MailClient.Credentials = new NetworkCredential("[email protected]", "passcode");
MailClient.Send(EmailMsg);
C#
-----------
using System.Net.Mail;
MailMessage EmailMsg = new MailMessage();
EmailMsg.From = new MailAddress("[email protected]");
EmailMsg.To.Add(new MailAddress("[email protected]"));
EmailMsg.Subject = "Customer_Questions";
EmailMsg.Body = "your Customers body";
EmailMsg.IsBodyHtml = true;
EmailMsg.Priority = MailPriority.Normal;
EmailMsg.BodyEncoding = Encoding.UTF8;
SmtpClient MailClient = new SmtpClient("mail.namannassar.com", 25);
MailClient.UseDefaultCredentials = false;
MailClient.Credentials = new NetworkCredential("[email protected]", "passcode");
MailClient.Send(EmailMsg);
Joseph Regan
18 July 2012 07:41 AM
Now you MUST use System.Net.Mail not System.Web.Mail or it won't work!
Michael Carr
01 August 2012 11:21 AM
Thanks for this update.
Ricardo Sánchez
28 August 2012 12:12 PM
It worked as expected with your suggested change, thank you!
Sabry Eassa
08 September 2012 03:25 AM
did any one try to send email from asp.net using System.Net.Mail on any arvixe server using 587 or 465 and SSL enabled, my code works fine on gmail using port 587 and SSL , but when i replace mail server to any of my accounts on arvixe , 465 always time out and 587 always "server dose not support secure connection , if i disable ssl it works on 587, same code works fine on port 25.
Appreciate any help.
Appreciate any help.
Michael Carr
25 September 2012 01:08 PM
If you can open a support ticket we will be glad to take a look
Liz Gee
12 September 2012 08:00 AM
I tried the above example, and mine didn't work.
Not sure if I have my email server correct.
string _from = "[email protected]";
SmtpClient smtp = new SmtpClient("mail.allergy-acupuncture.com");
smtp.Credentials = new System.Net.NetworkCredential(Convert.ToString(_from), "passcode");
smtp.UseDefaultCredentials = false;
// smtp.Host = "smtp.strawberry.arvixe.com";
smtp.Send(mail);
return smtp;
Not sure if I have my email server correct.
string _from = "[email protected]";
SmtpClient smtp = new SmtpClient("mail.allergy-acupuncture.com");
smtp.Credentials = new System.Net.NetworkCredential(Convert.ToString(_from), "passcode");
smtp.UseDefaultCredentials = false;
// smtp.Host = "smtp.strawberry.arvixe.com";
smtp.Send(mail);
return smtp;
Michael Carr
25 September 2012 12:48 PM
Thank you for sharing.
Ercan
15 October 2012 04:11 AM
I tried code like this with port 25 and host localhost didn't work.
Change
smtp.Credentials = new System.Net.NetworkCredential(Convert.ToString(_from), "passcode");
smtp.UseDefaultCredentials = false;
order.
Write
smtp.UseDefaultCredentials = false;
before.
Change
smtp.Credentials = new System.Net.NetworkCredential(Convert.ToString(_from), "passcode");
smtp.UseDefaultCredentials = false;
order.
Write
smtp.UseDefaultCredentials = false;
before.
Michael Carr
15 October 2012 10:21 AM
If you can open a support ticket we will be glad to take a look for you.
Rajat
18 March 2013 07:03 AM
Hello,
Please help me.
My website was developed by somebody. due to some dispute we have taken that website's source code and paste it to other website hosting provider. This website was developed in VB as a project. Now the problem is following:
There is a inquiry page in website. I want as any visitor submit their inquiry, one notification should come to my email ID from a given email ID. Currently it is happening but Email(from) notification is coming on my email ID is my developer's email ID. I want to remove his email ID and put my email ID. I have searched all source code but i could not find that email ID from which i am receiving notification.
Kindly help me. Please remember website is in Visual basic, language C#.
Thanks in advance.
Please help me.
My website was developed by somebody. due to some dispute we have taken that website's source code and paste it to other website hosting provider. This website was developed in VB as a project. Now the problem is following:
There is a inquiry page in website. I want as any visitor submit their inquiry, one notification should come to my email ID from a given email ID. Currently it is happening but Email(from) notification is coming on my email ID is my developer's email ID. I want to remove his email ID and put my email ID. I have searched all source code but i could not find that email ID from which i am receiving notification.
Kindly help me. Please remember website is in Visual basic, language C#.
Thanks in advance.
Michael Carr
19 March 2013 02:36 PM
You should hire a programmer who can correct the code for you. unfortunately we are unable to support coding related issues.
Charity Smith
27 May 2013 05:48 PM
Can someone please help me? The code below is what I've used on my site, but I seem to not be able to get any email sent from the site page. When someone visits site, I have a contact page that allows visitors to select a email button. If they click the button, it takes them to a page where they can fill out their email address, subject, and message. The code below is what I have attached to the submit (email) button to send the email. I receive no error code in Visual Studio or on the site. According to everything the email gets sent, but of course I never receive it in my inbox. Do I need to add something to the web.config file to help this code work? I'm at a lost and would appreciate any help.
Thanks,
Charity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
/// <summary>
/// Summary description for clsBusinessLayer
/// </summary>
public class clsBusinessLayer
{
public void SendEmail(string emailFrom, string emailTo, string emailSubject, string emailBody)
{
bool emailSent;
try
{
//instantiate a new MailMessage Object
MailMessage emailMessage = new MailMessage();
// passes and set's the variable (From) of the new MailMessage object (emailMessage)
//to (emailFrom) a new MailAddress object
emailMessage.From = new MailAddress(emailFrom);
// passes and set's the variable (To) of the new MailMessage object (emailMessage)
//to (emailTo) a new MailAddress object
emailMessage.To.Add(new MailAddress(emailTo));
//set's the emailMessage (emailSubject) variable is set to equal Subject
emailMessage.Subject = emailSubject;
//set the emailMeassage.Body variable to equal emailBody
emailMessage.Body = emailBody;
//set the emailMessage (IsBodyHtml) variable to true
emailMessage.IsBodyHtml = true;
//sets emailMessage Priority to Normal
emailMessage.Priority = MailPriority.Normal;
//instantiate a new SmtpClient Object
SmtpClient mySmtpClient = new SmtpClient();
//host for IIS
mySmtpClient.Host = "mail.aventurinesoftware-webtechnologies.com";
//instainiates a new Network Credential Object
//NetworkCredential netCred = new NetworkCredential();
//sets SmtpClient SecureSocketLayer to true
//mySmtpClient.EnableSsl = true;
//sets network credentials for username and password
//netCred.UserName = "Took this out for security, but on site it uses my username";
//netCred.Password = "*******, this of course would be my password";
//default port for IIS
mySmtpClient.Port = 993;
//send email message
mySmtpClient.Send(emailTo, emailFrom, emailSubject, emailBody);
emailSent = true;
}
catch (Exception )
{
Console.WriteLine("There was an error.");
emailSent = false;
Console.Read();
}
}
Thanks,
Charity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
/// <summary>
/// Summary description for clsBusinessLayer
/// </summary>
public class clsBusinessLayer
{
public void SendEmail(string emailFrom, string emailTo, string emailSubject, string emailBody)
{
bool emailSent;
try
{
//instantiate a new MailMessage Object
MailMessage emailMessage = new MailMessage();
// passes and set's the variable (From) of the new MailMessage object (emailMessage)
//to (emailFrom) a new MailAddress object
emailMessage.From = new MailAddress(emailFrom);
// passes and set's the variable (To) of the new MailMessage object (emailMessage)
//to (emailTo) a new MailAddress object
emailMessage.To.Add(new MailAddress(emailTo));
//set's the emailMessage (emailSubject) variable is set to equal Subject
emailMessage.Subject = emailSubject;
//set the emailMeassage.Body variable to equal emailBody
emailMessage.Body = emailBody;
//set the emailMessage (IsBodyHtml) variable to true
emailMessage.IsBodyHtml = true;
//sets emailMessage Priority to Normal
emailMessage.Priority = MailPriority.Normal;
//instantiate a new SmtpClient Object
SmtpClient mySmtpClient = new SmtpClient();
//host for IIS
mySmtpClient.Host = "mail.aventurinesoftware-webtechnologies.com";
//instainiates a new Network Credential Object
//NetworkCredential netCred = new NetworkCredential();
//sets SmtpClient SecureSocketLayer to true
//mySmtpClient.EnableSsl = true;
//sets network credentials for username and password
//netCred.UserName = "Took this out for security, but on site it uses my username";
//netCred.Password = "*******, this of course would be my password";
//default port for IIS
mySmtpClient.Port = 993;
//send email message
mySmtpClient.Send(emailTo, emailFrom, emailSubject, emailBody);
emailSent = true;
}
catch (Exception )
{
Console.WriteLine("There was an error.");
emailSent = false;
Console.Read();
}
}
Michael Carr
30 May 2013 09:37 AM
It can be hard to say since you have removed the username, but a common error is to use the hosting accounts main username and password when you should instead be using a full email account for the login and that email accounts associated password. If thats not it I would suggest opening a support ticket and we will take a quick look at it for you.
jeryymanly
20 January 2014 12:19 AM
you can try c# cdo email instead of smtp
http://csharp.net-informations.com/communications/csharp-cdo-email.htm
c# email
jery
http://csharp.net-informations.com/communications/csharp-cdo-email.htm
c# email
jery
Richard Rubin
21 February 2014 08:59 AM
Anyone get the solution for SSL email using port 465? I typically use GMAIL to handle sending/receiving my email but now I need a small app that resides on one of my machines to just send.
I can get port 587 to work just fine with a standard, non encrypted email. The minute I use port 465 and EnableSsl = true I get a timeout. Not an error connecting or sending, but a timeout (as if it can't find the port). Is there something special I need to do for my network credentials?
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
Any help is appreciated. Thanks!
I can get port 587 to work just fine with a standard, non encrypted email. The minute I use port 465 and EnableSsl = true I get a timeout. Not an error connecting or sending, but a timeout (as if it can't find the port). Is there something special I need to do for my network credentials?
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
Any help is appreciated. Thanks!
Michael Carr
28 February 2014 03:03 PM
This depends on where you are connecting from and what mail server you are using. For SSL you will need to connect to the servers hostname. If you need more help please open a support ticket.
Linda Rawson
10 March 2014 05:12 PM
Richard Rubin....did you ever get this working? I cannot get an outbound email to work for anything. Not non encrypted or SSL enabled. Same results as everyone else. It appears to successfully send but the email never shows up.
Michael Carr
12 March 2014 11:36 AM
Most likely this is an issue with the mail server host name that you are using. If you could create a support ticket we would be happy to check for you.
Francisco Monteiro
11 July 2014 06:51 AM
what is the number of e-mails of hours?
Can i send 461 emails on time or send 100 and more 100....?
Can i send 461 emails on time or send 100 and more 100....?
Michael Carr
22 July 2014 12:21 PM
None of our shared plans really support bulk emailing however the sending limits on them are 1000 per hour.
Dean
17 December 2014 05:03 PM
I was able to send emails via .Net
First I set up a mail account from my control panel.
For example, I created a mail account "[email protected]" with the password "OhHai!Kthxbai"
C# code to send emails using this account :
using System.Net.Mail;
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.To.Add(ToAddress);
mailMessage.From = new MailAddress(FromAddress);
mailMessage.Subject = Subject;
mailMessage.Body = Body;
client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Host = "mail.domain.com";
client.Port = 26;
client.Credentials = new System.Net.NetworkCredential("[email protected]", "OhHai!Kthxbai");
client.Send(mailMessage);
}
Hope this helps.
First I set up a mail account from my control panel.
For example, I created a mail account "[email protected]" with the password "OhHai!Kthxbai"
C# code to send emails using this account :
using System.Net.Mail;
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.To.Add(ToAddress);
mailMessage.From = new MailAddress(FromAddress);
mailMessage.Subject = Subject;
mailMessage.Body = Body;
client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Host = "mail.domain.com";
client.Port = 26;
client.Credentials = new System.Net.NetworkCredential("[email protected]", "OhHai!Kthxbai");
client.Send(mailMessage);
}
Hope this helps.