12

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?

SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
Nurlan
  • 2,860
  • 19
  • 47
  • 64

7 Answers7

12

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);
Waqar Janjua
  • 6,113
  • 2
  • 26
  • 36
  • Thanks, it works! But what to do if I do not want use gmail or hotmail. I want to use the service of some company, for example www.mycompany.com. Do I need any server configurations? Is it enough if I know smtp host and port? – Nurlan Jul 28 '12 at 20:14
  • 2
    @NurlanKenzhebekov I never use any service. Sending an email is an easy process. If you use any service then the company provide email domains, I think you only have to use smtp to send email, no such server configruation is required. – Waqar Janjua Jul 28 '12 at 20:19
7

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);
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
  • Thanks, it works! But what to do if I do not want use gmail or hotmail. I want to use the service of some company, for example www.mycompany.com. Do I need any server configurations? Is it enough if I know smtp host and port? – Nurlan Jul 28 '12 at 20:14
5

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.

Spikeh
  • 3,540
  • 4
  • 24
  • 49
2

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.

saintedlama
  • 6,838
  • 1
  • 28
  • 46
  • Thanks, it works! But what to do if I do not want use gmail or hotmail. I want to use the service of some company, for example www.mycompany.com. Do I need any server configurations? Is it enough if I know smtp host and port? – Nurlan Jul 28 '12 at 20:13
1
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/>" +
                                              //"<a href=\""></a><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/><a href=\"">www.Test.com</a></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 = "";
    }
0

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 :)

SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
0

Server.mappath does not exist. There is no Server object.

Clem
  • 69
  • 1
  • 8