20 tips for ASP. net mvc 3 development (5) [20 recipes for programming MVC 3]: Send a welcome email

Source: Internet
Author: User
Tags mailmessage smtpclient

Topics

Many websites require users to register or log on when accessing content or posting comments. As there are more and more such websites, it is very difficult for users to remember the sites and information they have registered. When a user submits the registration information, the website can send an email reminding the user that they have just signed the registration information so that they can query it later.

 

Solution

Implement the smtpclient class and mailmessage class to send a welcome email after user registration.

 

Discussion

To send an email, you must configure the SMTP server address, port, user name, and password. To make the configuration easier, we recommend that you store the information in the appsettings node of Web. config.

     <  Appsettings  > 

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

Enter available parameters in values of smtpserver, smtpport, smtpuser, and smtppass.

To better organize projects, we will create a new folder to include the mail sending classes. Right-click the project and choose "add"> "new folder" and name it "utils ". Right-click the newly created "utils" folder, select "add"-> "class", and name it "mailclient. cs ".

To facilitate access, the mailclient class is defined as a static class. In the future, when it is integrated with other systems, it can be directly used without the need to create new objects. Below is the complete mailclient classCode:

Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. net. mail;
Using System. net;
Using System. configuration;

Namespace Mvcapplication4.utils
{
Public Static Class Mailclient
{
Private Static Readonly Smtpclient client;

Static Mailclient ()
{
Client = New Smtpclient
{
Host =
Configurationmanager. deleettings [ " Smtpserver " ],
Port =
Convert. toint32 (
Configurationmanager. deleettings [ " Smtpport " ]),
Deliverymethod = smtpdeliverymethod. Network
};

Client. usedefacrecredentials = False ;
Client. Credentials = New Networkcredential (
Configurationmanager. deleettings [" Smtpuser " ],
Configurationmanager. deleettings [ " Smtppass " ]);
}

Private Static Bool Sendmessage ( String From , String To,
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 );
}
}
}

At the beginning of the class, reference the value from web. config and create an smtpclient class instance. The sendmessage method defined below is a private method and cannot be called directly from outside the class. This method is used to actually execute the sending function. This method creates a new mailmessage instance and sends it through the smtpclient object created previously. Finally, a sendwelcome function is created to accept the user's email address parameters and send a welcome email by calling the sendmessage method.

In the account controller, you can call the sendwelcome method to send an email immediately after registration or update through the Register Method:

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using System. Web. Routing;
Using System. Web. Security;
Using Mvcapplication4.models;
Using Mvcapplication4.utils;

Namespace Mvcapplication4.controllers
{
Public Class Accountcontroller: Controller
{
...
//
// Post:/account/register
[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)
{
// Send welcome email
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 above code is a basic example, which enables a user to send a welcome email to the user during the registration process. In modern society, automatic form processing is a great idea. In future use, we can add a "confirm your email address" link message in the email, the user must click the link in the welcome email to activate the account before logging on.

 

Reference

Stmpclient mailmessage Source Book Address Source Code

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.