Is it possible to send email from my computer(localhost) using asp.net project in C#?
Finally I am going to upload my project into webserver but I want to test it before uploading.
I've found ready source codes and tried run them in localhost, but neither of them work succesfully.
For example this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
namespace sendEmail
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_SendMail_Click(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage(
txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(mailObj);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
}
}
So how to send email using asp.net C#? Should I setup some server configurations?
Sending Email from Asp.Net:
MailMessage objMail = new MailMessage("Sending From", "Sending To","Email Subject", "Email Body");
NetworkCredential objNC = new NetworkCredential("Sender Email","Sender Password");
SmtpClient objsmtp = new SmtpClient("smtp.live.com", 587); // for hotmail
objsmtp.EnableSsl = true;
objsmtp.Credentials = objNC;
objsmtp.Send(objMail);
if you have a gmail account you can use google smtp to send an email
smtpClient.UseDefaultCredentials = false;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential(username,passwordd);
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
Your code above should work fine, but you need to add the following to your web.config (as an alternative to any code-based SMTP configuration):
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="your.smtpserver.com" port="25" userName="smtpusername" password="smtppassword" />
</smtp>
</mailSettings>
</system.net>
If you don't have access to a remote SMTP server (I use my own POP3 / SMTP email details), you can set up an SMTP server in your local IIS instance, but you may run in to issues with relaying (as most ISP consumer IP addresses are black listed).
A good alternative, if you don't have access to an SMTP server, is to use the following settings instead of the above:
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="C:\mail"/>
</smtp>
</mailSettings>
</system.net>
This will create a hard disk copy of the email, which is pretty handy. You will need to create the directory you specify above, otherwise you will receive an error when trying to send email.
You can configure these details in code as per other answers here (by configuring the properties on the SmtpClient object you have created), but unless you're getting the information from a data source, or the information is dynamic, it's superfluous coding, when .Net already does this for you.
You can send email from ASP.NET via C# class libraries found in the System.Net.Mail namespace. take a look at the SmtpClient class which is the main class involved when sending emails.
You can find code examples in Scott Gu's Blog or on the MSDN page of SmtpClient.
Additionally you'll need an SMTP server running. I can recommend to use SMTP4Dev mail server that targets development and does not require any setup.
Create class name SMTP.cs then
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
/// <summary>
/// Summary description for SMTP
/// </summary>
public class SMTP
{
private SmtpClient smtp;
private static string _smtpIp;
public static string smtpIp
{
get
{
if (string.IsNullOrEmpty(_smtpIp))
_smtpIp = System.Configuration.ConfigurationManager.AppSettings["smtpIp"];
return _smtpIp;
}
}
public SMTP()
{
smtp = new SmtpClient(smtpIp);
}
public string Send(string From, string Alias, string To, string Subject, string Body, string Image)
{
try
{
MailMessage m = new MailMessage("\"" + Alias + "\" <" + From + ">", To);
m.Subject = Subject;
m.Priority = MailPriority.Normal;
AlternateView av1 = AlternateView.CreateAlternateViewFromString(Body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);
if (!string.IsNullOrEmpty(Image))
{
string path = HttpContext.Current.Server.MapPath(Image);
LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
av1.LinkedResources.Add(logo);
}
m.AlternateViews.Add(av1);
m.IsBodyHtml = true;
smtp.Send(m);
}
catch (Exception e)
{
return e.Message;
}
return "sucsess";
}
}
then
on aspx page
protected void lblSubmit_Click(object sender, EventArgs e)
{
//HttpContext.Current.Response.ContentType = "text/plain";
//Guid guid = Guid.NewGuid();
string EmailMessage = "<html>" +
"<head>" +
"<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" +
"</head>" +
"<body style=\"text-align:left;direction:ltr;font-family:Arial;\" >" +
"<style>a{color:#0375b7;} a:hover, a:active {color: #FF7B0C;}</style>" +
"<img src=\"" width=\"190px\" height= \"103px\"/><br/><br/>" +
"<p>Name: " + nameID.Value + ",<br/><br/>" +
"<p>Email: " + EmailID.Value + ",<br/><br/>" +
"<p>Comments: " + commentsID.Text + "<br/><br/>" +
// "Welcome to the Test local updates service!<br/>Before we can begin sending you updates, we need you to verify your address by clicking on the link below.<br/>" +
//"<br/><br/>" +
//"We look forward to keeping you informed of the latest and greatest events happening in your area.<br/>" +
//"If you have any questions, bug reports, ideas, or just want to talk, please contact us at <br/><br/>" +
//"Enjoy! <br/>" + commentsID.Text + "<br/>" +
//"Test<br/>www.Test.com</p>" +
"</body>" +
"</html>";
lblThank.Text = "Thank you for contact us.";
// string Body = commentsID.Text;
SMTP smtp = new SMTP();
string FromEmail = System.Configuration.ConfigurationManager.AppSettings["FromEmail"];
string mailReturn = smtp.Send(EmailID.Value, "", FromEmail, "Contact Us Email", EmailMessage, string.Empty);
//HttpContext.Current.Response.Write("true");
nameID.Value = "";
EmailID.Value = "";
commentsID.Text = "";
}
Below is the solution for you if you do not want to use gmail or hotmail:
SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("info#MyWebsiteDomainName.com", "myIDPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("info#MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info#MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("MyEmailID#gmail.com"));
smtpClient.Send(mail);
Hope it help :)
Server.mappath does not exist. There is no Server object.
Related
System.Security.SecurityException: Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
When i work on the local server on a visual studio then their is no problem
when i deploy this code and run the online then is face this problem
error on the server after deploying but on a local server there is no problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void send_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailfrom = "example#gmail.com";
string password = "*********";
string subject = "Contact Form Data";
string emailto = "example#gmail.com";
string name = n.Value;
string useremail = em.Value;
string phone = tel.Value;
string dept = dep.Value;
string dest = des.Value;
string adu = ad.Value;
string body = "Name: " + name + " ;" + " Email: " + useremail + " ;" + "Telephone: " + phone + " ;" + " Departure Place: " + dept + " ;" + "Destination Place: " + dest + " ;" + " Adults: " + adu + " ;" + " ;" + "Children: " + chil + " ;";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailfrom);
mail.To.Add(emailto);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailfrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
}
There is two solution.
1) A low security level doesn't allow you to specify the smtp port. Default is port 25. Although my ISP specifies port 587,Use port 25.
2) Add Code in Web.config.
<configuration>
<system.web>
.....
<trust level="Full" originUrl=""/>
</system.web>
</configuration>
Hope its Work!!
Happy Coding!!
Try to change the SMTP port to port 25. I think it should work.
The error is caused by your server's trust configuration. Usually the trust level is sufficient for this library to work but it might be because of special trust configuration on your server or maybe you are deploying on Linux server or something.
Ok it doesn't matter why but you can solve it by manually granting trust to that library by adding this node in your Web.config file:
<system.web>
<securityPolicy>
<fullTrustAssemblies>
<add assemblyName="System.Net.Mail.SmtpPermission" version="4.0.0.0" publicKey="b77a5c561934e089"/>
</fullTrustAssemblies>
</securityPolicy>
</system.web>
Please check the info I used with the error data. If error changed with other assembly name add them as well.
For more information you can see these two resources:
https://msdn.microsoft.com/en-us/library/wyts434y.aspx
https://msdn.microsoft.com/en-us/library/aa302361.aspx
im using Asp.net And I have the Umbraco Cms on my project
i implemented The Send message using razor syntax
im submitting a from to the following razor syntax
#{ if (IsPost)
{
string name = Request["name"];
string email = Request["email"];
string phone = Request["phone"];
string city = Request["city"];
string note = Request["note"];
NetworkCredential basicCredential =new NetworkCredential("*****#gmail.com", "******");
MailMessage mail = new MailMessage();
//var from = new MailAddress(Email.Text);
mail.From = new MailAddress(email);
mail.To.Add("tupacmuhammad5#gmail.com");
mail.Subject = "Torcan WebSite Contact Us";
mail.IsBodyHtml = false;
mail.Body = "You just got a contact email:\n" +
"Name: " + name + "\n"
+ "Email: " + email + "\n"
+ "TelePhone: " + phone + "\n"
+ "Address: " + city + "\n"
+ "Message: " + note + "\n";
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = basicCredential;
smtp.EnableSsl = true;
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
finally
{
smtp.Dispose();
}
}
}
it works perfect on My localHost But on a live server its thorws a runtime error "after i remove the try catch "
i cant find out what seems to be problem
im writing this code in umbraco backoffice tamplate i have the server on onther country and i dont have access to it any help ? please ?
The Problem was that the Server is located in Germany so when the server tries to open my Gmail account. its a different country and never seen action from there.
so all i had to do is to open my gmail via remote access on the server machine via a browser and confirmed it was me then every thing worked perfectly.
I have anasp.net web form which on click of a button sends i want an email to be sent to my Microsoft outlook email account. I have done this on other
websites but that was using hotmail but all external web email providers are blocked by the companies firewall (as i tried setting up a gmail account) so
i need to use Outlook but i have not idea on how to implent this and solutions i have seen on Google dont seem to work. I dont know if it'll make a
difference or not but i have been informed that the users password epxires every 30days so i suspect i'll need to use windows authenication or something
but not sure.
I'm not sure on how Outlook send the email as i know from past experience from using hotmail that the email is just sent on click of the button but i'm
not sure if outlook would open the email window for the user to click the send button. If it does, i need the information captured on the webform to be
containd in the email and the content of the email body not to be altered (if this can be done, again not ot sure if it can but not a problem if it
can't).
Below is the code i used for when i tried gmail but as i said i was told it wouldnt be allowed.
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
#region Email
try
{
//Creates the email object to be sent
MailMessage msg = new MailMessage();
//Adds your email address to the recipients
msg.To.Add("MyEmailAddress#Test.co.uk");
//Configures the address you are sending the email from
MailAddress address = new MailAddress("EmailAddress#Test.com");
msg.From = address;
//Allows HTML to be used when setting up the email body
msg.IsBodyHtml = true;
//Email subjects title
msg.Subject = "Place Suggestion";
msg.Body = "<b>" + lblPlace.Text + "</b>" + " " + fldPlace.Text
+ Environment.NewLine.ToString() +
"<b>" + lblLocation.Text + "</b>" + " " + fldLocation.Text
+ Environment.NewLine.ToString() +
"<b>" + lblName.Text + "</b>" + " " + fldName.Text;
//Configures the SmtpClient to send the mail
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true; //only enable this if the provider requires it
//Setup credentials to login to the sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("MyEmailAddress#Test.co.uk", "MyPassword");
client.Credentials = credentials;
//Send the email
client.Send(msg);
}
catch
{
//Lets the user know if the email has failed
lblNotSent.Text = "<div class=\"row\">" + "<div class=\"col-sm-12\">" + "There was a problem sending your suggestion. Please try again."
+ "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-sm-12\">" + "If the error persists, please contact Antony." + "</div>" +
"</div>";
}
#endregion
}
edit 2: Now we have established your going through exchance this is how my code has always worked
SmtpClient sptmClient = new SmtpClient("exchange server name")
MailMessage m = new MailMessage();
m.To.Add(new MailAddress("Address"));
m.From = new MailAddress("");
m.Subject = "";
m.Body = "";
m.IsBodyHtml = true;
sptmClient.Send(m);
but there is another answer on here that uses outlook interoperlation that might work better for you
With Exchange it must work.
test this :
using Outlook = Microsoft.Office.Interop.Outlook;
private void SendWithExchange()
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem mail = oApp.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Exemple à tester";
Outlook.AddressEntry currentUser =
oApp.Session.CurrentUser.AddressEntry;
if (currentUser.Type == "EX")
{
Outlook.ExchangeUser manager =
currentUser.GetExchangeUser();
mail.Recipients.Add(manager.PrimarySmtpAddress);
mail.Recipients.ResolveAll();
//mail.Attachments.Add(#"c:\sales reports\fy06q4.xlsx",
// Outlook.OlAttachmentType.olByValue, Type.Missing,
// Type.Missing);
mail.Send();
}
}
Intro: I am supporting a piece of code that sends a welcome/confirm mail upon successful registration to a site.
The SMTP client times out before sending can complete. According to our Ops department, I am using the correct credentials and SMTP server IP address.
What I want to do is hook into any handshaking, connection, sending, etc events so that I can figure out exactly why the process times out. I've set Server.ScriptTimeOut to 500 seconds on that page, so it can't just be a busy server problem.
My question is this: what events can I handle during this process. The only one I see exposed in SMTPClient is SendCompleted. But I imagine there must be a way to get access to something more low-level?
For reference, here's the code:
//Create and send email
MailMessage mm = new MailMessage();
try
{
mm.From = new MailAddress("admin#site.com");
mm.To.Add(new MailAddress(Recipient));
mm.Subject = Subject;
mm.Body = MailBody;
mm.IsBodyHtml = true;
var c = new NetworkCredential("admin#site.com", "YeOlePassword");
SmtpClient smtp = new SmtpClient("127.0.0.1");//not really, just hiding our SMTP IP from StackOverflow
smtp.UseDefaultCredentials = false;
smtp.Credentials = c;
smtp.Send(mm);
}
catch (Exception x)
{
DateTime CurrentDateTime = DateTime.Now;
String appDateTime = CurrentDateTime.ToString();
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + x.Message;
StreamWriter streamwriter = new StreamWriter(File.Open(MapPath("~/TransactionLog.txt"), FileMode.Append, FileAccess.Write, FileShare.Write));
//Append to file
streamwriter.WriteLine(transactionLogEntry);
//Close file
streamwriter.Close();
}
The error that's logged is simply that a timeout occured while sending a mail to the supplied email address.
I use this to get the buried SMTP messages out.
String transactionLogEntry = "To: " + Recipient + " " + appDateTime + " " + GetFullErrorMessage(x);
.
.
.
private string GetFullErrorMessage(Exception e)
{
string strErrorMessage = "";
Exception excpCurrentException = e;
while (excpCurrentException != null)
{
strErrorMessage += "\"" + excpCurrentException.Message + "\"";
excpCurrentException = excpCurrentException.InnerException;
if (excpCurrentException != null)
{
strErrorMessage += "->";
}
}
strErrorMessage = strErrorMessage.Replace("\n", "");
return strErrorMessage;
}
In my experience, from what you are describing it is related to your SMTP port being blocked by and ISP or your server/web host. Good luck!
I am trying to programmatically access a Windows application app.config file. In particular, I am trying to access the "system.net/mailSettings"
The following code
Configuration config = ConfigurationManager.OpenExeConfiguration(configFileName);
MailSettingsSectionGroup settings =
(MailSettingsSectionGroup)config.GetSectionGroup(#"system.net/mailSettings");
Console.WriteLine(settings.Smtp.DeliveryMethod.ToString());
Console.WriteLine("host: " + settings.Smtp.Network.Host + "");
Console.WriteLine("port: " + settings.Smtp.Network.Port + "");
Console.WriteLine("Username: " + settings.Smtp.Network.UserName + "");
Console.WriteLine("Password: " + settings.Smtp.Network.Password + "");
Console.WriteLine("from: " + settings.Smtp.From + "");
fails to give the host, from. it only gets the port number. The rest are null;
This seems to work ok for me:
MailSettingsSectionGroup mailSettings =
config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
if (mailSettings != null)
{
string smtpServer = mailSettings.Smtp.Network.Host;
}
Here's my app.config file:
<configuration>
<system.net>
<mailSettings>
<smtp>
<network host="mail.mydomain.com" />
</smtp>
</mailSettings>
</system.net>
</configuration>
However, as stated by Nathan, you can use the application or machine configuration files to specify default host, port, and credentials values for all SmtpClient objects. For more information, see <mailSettings> Element on MDSN.
Not sure if this helps, but if you are trying to make a SmtpClient, that will automatically use the values in your config file if you use the default constructor.
I used the following to access the mailSettings:
var config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var mailSettings = config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
private void button1_Click(object sender, EventArgs e)
{
try
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mailSettings = config.GetSectionGroup("system.net/mailSettings")
as MailSettingsSectionGroup;
MailMessage msg = new MailMessage();
msg.Subject = "Hi Raju";
msg.To.Add("raju#hasten.in");
msg.From = new MailAddress("hasten.c#hasten.in");
msg.Body = "Hello Raju here everything is fine.";
//MailSettingsSectionGroup msetting = null;
string mMailHost = mailSettings.Smtp.Network.Host;
SmtpClient mailClient = new SmtpClient(mMailHost);
mailClient.Send(msg);
MessageBox.Show("Mail Sent Succesfully...");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}