简体   繁体   中英

Sending mail from ASP.NET application

Is there a way to send mail from an asp.net application? Right now I'm trying to figure out how to create confirmation emails when you sign up for a service.

System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);

Check out the SmtpClient class . For example code, see this answer from Shlomi.

Have a look at the followin link it goes into depth of hwo to send mail from Asp.net:

http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/

this code will get you started using (MailMessage mm = new MailMessage()) {

                mm.From = new MailAddress("noreply@mail.com");

                SmtpClient client = new SmtpClient("127.0.0.1");

                string smtpServerUserName = "username";
                string smtpServerPassword = "password"; 
            if (smtpServerUserName.HasValue() && smtpServerPassword.HasValue())
                {
                    client.Credentials = new NetworkCredential(smtpServerUserName, smtpServerPassword);
                }
                smtpServerPort = "";
                if (smtpServerPort.HasValue())
                {
                    client.Port = Convert.ToInt32(smtpServerPort, CultureInfo.InvariantCulture);
                }
                mm.Priority = MailPriority.Normal;

                mm.IsBodyHtml = false;

                mm.Subject = subject;
                mm.To.Add(new MailAddress("you@home.com"));
                mm.Body = body;

                client.Send(mm);
            }
        }

where hasvalue() is just a extensionmethod which inverts string.IsNullOrEmpty()

you can use papercut (http://papercut.codeplex.com/) to test it on your local pc, then use 127.0.0.1 as ipaddress without any smtpusername, password or portnumber.

/// <summary>
    /// checks if a string is null or empty (hasvalue = false if null or empty)
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool HasValue(this string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return false;
        }
        return true;
    }

Check this generic guide on sending emails in .NET:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM