20 secrets of MVC3-(5) Send a welcome email

Source: Internet
Author: User
Tags mailmessage smtpclient

 

Scenario

Many websites require people to register before accessing the content or making comments. How can a website such as Niu Mao make people remember every website they have registered. During the registration process, you can send an email to remind users that they have just registered. In this way, they may return to your website later.

Solution

After the user registers, use SmtpClient and MailMessage to send email notifications.

Discussion

Before sending an email, you need to configure an SMTP server, port, user name, and password. To simplify the configuration, we recommend that you configure it in the appsetting of web. config.

<Deleetask>

 

<Add key = "webpages: Version" value = "1.0.0.0"/>

 

<Add key = "ClientValidationEnabled" value = "true"/>

 

<Add key = "UnobtrusiveJavaScriptEnabled" value = "true"/>

 

<Add key = "smtpServer" value = "localhost"/>

 

<Add key = "smtpPort" value = "25"/>

 

<Add key = "smtpUser" value = ""/>

 

<Add key = "smtpPass" value = ""/>

 

<Add key = "adminEmail" value = "no-reply@no-reply.com"/>

 

</AppSettings>

 

If necessary, update these values to reflect your SMTP server, port, username, and password.

Tip: You can also use the ASP. NET Configuration tool of Visual studio to configure.

 

Select Application> Configure SMTP email settings

 

To facilitate the organization of the project structure, we need to create a new folder and a new class to include the necessary email sending function.

Right-click the project and choose add> Create folder and name it Uitls. Right-click a new class and name it MailClient. cs.

The MailClient class and its functions are defined as static for ease of use. In the future, when he is integrated into a new function, he does not need to create a new instance for it. Below is a complete MailClient class:

Using System;

Using System. Collections. Generic;

Using System. Configuration;

Using System. Linq;

Using System. Net;

Using System. Net. Mail;

Using System. Web;

 

Namespace MvcApplication. Utils

{

 

Public static class MailClient

{

Private static readonly SmtpClient Client;

Static MailClient ()

{

Client = new SmtpClient

{

Host =

ConfigurationManager. configurettings ["SmtpServer"],

Port =

Convert. ToInt32 (

ConfigurationManager. receivettings ["SmtpPort"]),

DeliveryMethod = SmtpDeliveryMethod. Network

};

Client. usedefacrecredentials = false;

Client. Credentials = new NetworkCredential (

ConfigurationManager. configurettings ["SmtpUser"],

ConfigurationManager. deleetpipeline ["SmtpPass"]);

}

Private static bool SendMessage (string from, string,

String subject, string body)

{

MailMessage mm = null;

Bool isSent = false;

Try

{

// Create our message

Mm = new MailMessage (from, to, subject, body );

Mm. DeliveryNotificationOptions =

DeliveryNotificationOptions. OnFailure;

// Send it

Client. Send (mm );

IsSent = true;

}

// Catch any errors, these shoshould be logged and

// Dealt with later

Catch (Exception ex)

{

// If you wish to log email errors,

// Add it here...

Var exMsg = ex. Message;

}

Finally

{

Mm. Dispose ();

}

Return isSent;

}

Public static bool SendWelcome (string email)

{

String body = "Put welcome email content here ...";

Return SendMessage (

ConfigurationManager. deleettings ["adminEmail"],

Email, "Welcome message", body );

}

}

}

First, create a new SmtpClient instance through webconfig configuration. Then create a SendMessage function. This function is private and should not be called directly. This function is called when it is actually executed and sent. It creates a new MailMessage object and sends it through the SmtpClient object built by the front-end vertex. The SendWelcome function is used to create an email Receiving address. It generates a common message to send your email. It is sent through the SendMessage function.

To send email notifications after registration. The register action in Account controller must call the SendWelcome method after the user successfully creates an Account.

[HttpPost]

Public ActionResult Register (RegisterModel model)

{

If (ModelState. IsValid)

{

// Attempt to register the user

MembershipCreateStatus createStatus;

Membership. CreateUser (model. UserName, model. Password, model. Email, null, null, true, null, out createStatus );

 

If (createStatus = MembershipCreateStatus. Success)

{

MailClient. SendWelcome (model. Email );

FormsAuthentication. SetAuthCookie (model. UserName, false/* createPersistentCookie */);

Return RedirectToAction ("Index", "Home ");

}

Else

{

ModelState. AddModelError ("", ErrorCodeToString (createStatus ));

}

}

 

// If we got this far, something failed, redisplay form

Return View (model );

}

The front-end code is a basic example. In today's society, it is a good idea to process existing applications in an automated manner.

You can further extend this example. A verification message is included in your welcome email. This will verify the validity of your email address. Ask him to click the link in the welcome email. Then he can log in.

For more information, see

SmtpClient and MailMessage

Translator's note: In. NET 4.0, Microsoft has provided a new helper "Webmail ". More convenient.

If you are interested, you can check WebMail.


 

Author technical brother

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.