How to send mail using smtpmail in asp.net: instance

Source: Internet
Author: User
Tags base64 how to send mail mailmessage

. NET, the function of sending mail has been encapsulated into the System.Web.Mail namespace of the. NET Framework, and using this namespace, it is easy to build a mail-sending program that requires only a good structure of the SMTP server in Windows.

System.Web.Mail namespaces. This named control contains the following objects and three properties:
Included objects:

MailAttachment: Object classes related to mail attachments
MailMessage: Message body
SmtpMail: The SMTP protocol that is responsible for sending mail.

List of properties:

MailEncoding: Encoding of messages (Base64,uuencode)
MailFormat: The format of the message (HTML hypertext format, text plain text format)
Mailpriority: Message priority (High, Medium, low)

To build a MailMessage object:
  
The MailMessage object is the host body of the message, and you can usually build the MailMessage object first and then set its properties to

To build your mail program, here are some common properties listed below:

Attachments: Mail Attachment
BCC: Dark Send Address
Body: Mail Subject
BodyFormat: Message Format (html,text)
CC: CC Address
From: Sender's address
Priority: Message priority (high, Medium,low)
Subject: Message subject
To: Recipient address
Urlcontentbase: URL encoding in an HTML-formatted message
Urlcontentlocation: Priority of message information (high, Medium,low)

Send mail using SmtpMail
  
After building the MailMessage object, you also need to use another object-smtpmail-to send the message, SmtpMail has a very

Important: Send, the method has two different usages, one of which can only send the entire MailMessage object:
Smtpmail.send (Myemailobject);

Another allows you to specify the sender, the e-mail address, the subject of the message, the subject of the message, and then send it:

Smtpmail.send (Strfrom, Strto, Strsubject, strbody);
Now, let's take a look at a complete example, in this case, I first create a MailMessage object, then set some properties, and then use the SmtpMail object to send it out:

<%@ Page language= "C #"%>
<script language= "C #" runat= "Server" >


void Page_Load ()
{
CREATE A MAIL Message
System.Web.Mail.MailMessage myemail = new System.Web.Mail.MailMessage ();


SET message PARAMETERS
Myemail.from = "agent@mypersonalshoppers.com";
myemail.to = "john@johnsmith.com";
Myemail.subject = "Product availability Notice";
Myemail.bodyformat = System.Web.Mail.MailFormat.Html;
Myemail.body = "The sunglasses you expressed interest in are now";


SEND the message
System.Web.Mail.SmtpMail.Send (Myemail);


UPDATE STATUS
Lblmailstatus.text = "Mail successfully sent.";
}


</script>


<body>


<asp:label id= "Lblmailstatus" runat= "Server"/>


</body>
<%@ Page language= "VB"%>


<script language= "VB" runat= "Server" >


Sub Page_Load ()
' CREATE A MAIL message '
Dim Myemail as System.Web.Mail.MailMessage = new System.Web.Mail.MailMessage ()


' SET message PARAMETERS
Myemail.from = "Agent@mypersonalshoppers.com"
myemail.to = "John@johnsmith.com"
Myemail.subject = "Product availability Notice"
Myemail.bodyformat = System.Web.Mail.MailFormat.Html
Myemail.body = "The sunglasses you expressed interest in are now in the stock."


' SEND the message
System.Web.Mail.SmtpMail.Send (Myemail)


' UPDATE STATUS
Lblmailstatus.text = "Mail successfully sent."
End Sub


</script>


<body>
<asp:label id= "Lblmailstatus" runat= "Server"/>
</body>

Two. .............

In the ASP, you can send a simple message by calling the CDONTS component, which is natural in the asp.net. The difference is that, in the. Net framework, this component is encapsulated into the System.Web.Mail namespace.


A typical mail-sending program is as follows:
<%@ Import namespace= "System.Web.Mail"%>
<script runat= "Server" >
MailMessage mail=new MailMessage ();
Mail. From= "service@brookes.com";
Mail. To= "Brookes@brookes. COM ";
Mail. Bodyformat=mailformat.text;
Mail. body= "a test SMTP mail.";
Mail. Subject= "R u OK?";
smtpmail.smtpserver= "localhost";
Smtpmail.send (mail);
</script>


Typically, the system calls the default SMTP virtual server with IIS to deliver mail. However, you will often encounter such error prompts:

The server rejected one or more recipient addresses. The server response was:550 5.7.1 Unable to relay for brookes@brookes.com

There is an important reason for this error, in addition to the possibility of an incorrect address. As mentioned above, IIS does not carry true messaging functionality, but simply borrows an "SMTP virtual server" to enable forwarding of messages. In MSDN, you have the following tips:

If the local SMTP server (included in Windows 2000 and Windows Server 2003) is behind a firewall that blocks any direct SMTP traffic (via port 25), you will need to find out if there are any smart hosts available on the network that can be used to transfer to the Internet SMTP message.
A smart host is an SMTP server that can relay outgoing e-mail messages sent directly to the Internet from an internal SMTP server. A smart host should be able to connect to both the internal network and the Internet for use as an e-mail gateway.

Open the Default SMTP virtual Server-Properties-access-relay restrictions, and you can see that this forwarding or relaying function is limited. In the Limit list, add the IP addresses of the hosts that need to use this server to resolve the issues mentioned above.

If you do not use an SMTP virtual server with IIS and use other real mail servers, such as Imail,exchange, you often encounter problems with the server needing to send a sender authentication (ESMTP). An error occurs when you use a server that needs to verify the sender identity:

The server rejected one or more recipient addresses. The server response was:550 not local host ckocoo.com, not a gateway

Previously in ASP, there was no solution to this problem, and only the CDO component (CDONTS's parent component) could be used directly:
Conf. Fields[cdoconfiguration.cdosmtpauthenticate]. Value=cdoprotocolsauthentication.cdobasic;
Conf. Fields[cdoconfiguration.cdosendusername]. Value= "Brookes";
Conf. Fields[cdoconfiguration.cdosendpassword]. Value= "XXXXXXX";

This requirement is clearly taken into account in the. Net Framework 1.1, which adds a fields set to the MailMessage component that increases the issue of sender authentication in the ESMTP mail server. However, this method applies only to the. NET Framework 1.1 and does not apply to the. NET Framework version 1.0. The mail-sending program with sender authentication is as follows:


<%@ Import namespace= "System.Web.Mail"%>
<script runat= "Server" >
MailMessage mail=new MailMessage ();
Mail. From= "service@brookes.com";
Mail. To= "brookes@brookes.com";
Mail. Bodyformat=mailformat.text;
Mail. body= "a test SMTP mail.";
Mail. Subject= "R u OK?";
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); Basic Authentication
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/sendusername", "Brookes"); Set your username here
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/sendpassword", "Walkor"); Set your password here
Smtpmail.smtpserver= "Lsg.moon.net";
Smtpmail.send (mail);
</script>


With this method, you can finally no longer need to rely on JMail, Easymail, and other third-party components, and only simple use of Smtpmai can l complete the delivery of mail.

Three

<% @Import namespace= "System.Web.Mail"%>
<script language= "C #" runat= "Server" >
void Sendbutton_click (Object Sender,eventargs e)
{
MailMessage mailobj = new MailMessage ();
String strFileName;
Strfilename= "";
if (emailfrom.text!= "")
{
Mailobj.from = Emailfrom.text;
}

if (emailto.text!= "")
{
mailobj.to = Emailto.text;
}
  
if (emailcc.text!= "")
{
mailobj.cc = Emailcc.text;
}
  
if (emailbcc.text!= "")
{
MAILOBJ.BCC = Emailbcc.text;
Mailobj.bodyformat = Mailformat.text;
mailobj.priority = Mailpriority.normal;
Mailobj.subject = Emailsubject.text;
Mailobj.body = Emailbody.text;
Strfilename=emailfile.postedfile.filename;
}
if (strfilename!= "")
{
MAILOBJ.ATTACHMENTS.ADD (New MailAttachment (strFileName));
Smtpmail.smtpserver = "";
Smtpmail.send (Mailobj);
Panelsendemail.visible = false;
Panelmailsent.visible = true;
}
}
</script>
<body>
<asp:panel id= "Panelsendemail" runat= "Server" >
<form method= "Post" enctype= "Multipart/form-data" runat= "Server" >
<b> Please enter email address:</b>
<asp:textbox id= "Emailfrom" size= runat= "Server"/>
<p>
<b> Please enter the Mail destination address:</b>
<asp:textbox id= "Emailto" size= runat= "Server"/>
<p>
<b> Please enter the message cc address:</b>
<asp:textbox id= "EMAILCC" size= runat= "Server"/>
<p>
<b> Please enter the email address:</b>
<asp:textbox id= "EMAILBCC" size= runat= "Server"/>
<p>
<b> Please enter the message subject:</b>
<asp:textbox id= "EmailSubject" size= runat= "Server"/>
<p>
<b> Please enter the message body:</b>
<asp:textbox id= "Emailbody" textmode= "MultiLine"
columns= "rows=" runat= "Server"/>
<p>
<b> Please add the attachment name:</b>
<input id= "Emailfile" type= "file" runat= "Server" size= ""/>
<asp:button runat= "Server" id= "Sendbutton" text= "Send"
onclick= "Sendbutton_click"/>
</form>
</asp:panel>
<asp:panel id= "panelmailsent" runat= "Server" visible= "False" >
Your message has been successfully sent and you are welcome to use it again.
</asp:panel>
</body>

Four Using System.Web.Mail;
2)
MailMessage mail = new MailMessage ();
Mail. to = "me@mycompany.com";
Mail. from = "you@yourcompany.com";
Mail. Subject = "This is a test email.";
Mail. BODY = "Some text goes Here";
Mail. BodyFormat = mailformat.html;//set to Html format
Set to require user authentication
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
Set authentication username (change My_username_here to your authentication user name)
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/sendusername", "My_username_here");
Set the authentication password (change password to your authentication password)
Mail. Fields.Add ("Http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");
Smtpmail.smtpserver = "mail.mycompany.com"; Mail server address
Smtpmail.send (mail);

Five ...........

This article illustrates the many possibilities of sending emails in asp.net, covering such aspects as email format, priority, attachment and email encoding.

Asp. NET is given a new object to send email, named SmtpMail. When you use the SmtpMail object to send e-mail from a asp.net page, you can follow these simple steps:

▲ contains the namespaces required for the class of the message;
▲ example an information object, set the attribute;
▲ send a message using the Send method of the SmtpMail object instance.

Now we're going to take a step-by-step look at the process of sending emails from a asp.net page. We use VB to illustrate this example, the final will include VB and C # complete code.

First step: Include namespaces

Introduce the System.Web.Util namespace in the ASP.net page, which includes all the objects necessary to send an email. These objects are:

SmtpMail: Represents the mail system for sending emails.
MailMessage: Represents a message whose properties include the sender address, the recipient address, and so on.
MailFormat: Represents the format of information: HTML, text, and so on.
MailAttachment: Represents an email attachment.
mailencoding enum: Any encoding that represents Base64 or uuencode. Value range: Base64, UUencode
mailpriority enum: Used to set precedence for information. Values are: High, low, general.
<% @Import Namespace = "System.Web.Util"%>

Step Two: Example MailMessage object

Use the following statement to sample the MailMessage object:

Dim Mailobj as New MailMessage

Prepares the message with the properties of the MailMessage object. The MailMessage object has the following properties:

From: Email Address of sender
To: The email address of the recipient
The theme of Subject:email
The main body of the Body:email
Cc:email CC's recipient list
Bcc:email List of recipients to send secretly
Priority: Priority of information: high, low, or general
Bodyencoding: The encoding of an information body, if any, is Base64 or uuencode
BodyFormat: Format of information: Html or text
Attachments: A list of MailAttachment objects attached to an email, mainly a reference to the collection of objects

The following code demonstrates the use of MailMessage object properties, which represent a message that will be created in this example, to be sent using the SmtpMail object. In the example, mailobj references an example of an information object:

Mailobj.from = "Abc@mydomain.com"
Mailobj.to = Request.Form ("to")
Mailobj.subject = "Subject of the Mail"
Mailobj.body = "Message of the Mail"

Step three: Send email

At this point, we can use the Send method of the SmtpMail object to send the message:

Smtpmail.send (Mailobj)

Full instance

Finally, we combine the attributes explained above in a complete example. To illustrate the full possibility of sending an email with asp.net, we also include some "tips". Here is a complete example of using vb.net:

<% @page language= "VB"%>
<% @Import namespace= "System.Web.Util"%>
<HTML><BODY>
<script language= "VB" runat= "Server" >
' This is called on the ' server ' when the submit
' button is clicked on the client and ' the page
' Posts back to itself
Sub SendMail (Obj as Object, E as EventArgs)
' Instantiate a MailMessage object. This serves as a message object
' On which we can set properties.
Dim Mailobj as New MailMessage
' Set the ' and ' to address ' email
Mailobj.from = Request.Form ("from")
Mailobj.to = Request.Form ("to")
Mailobj.subject = "Subject of the Mail"
Mailobj.body = "Body of the Mail"
' optional:html format for the email
Mailobj.bodyformat = mailformat.html
' Optional:encoding for the message
mailobj.bodyencoding = Mailformat.base64
' Optional:set the priority '
Mailobj.priority = Mailpriority.high
' Optional:attach a file to the email.
' Here we are have created a MailAttachment object to
' Attach a file to the ' email
MAILOBJ.ATTACHMENTS.ADD (New MailAttachment ("C:/test.doc"))
' Send the ' email using the SmtpMail object
Smtpmail.send (Mailobj)
End Sub
</SCRIPT>
<asp:label id= "headingmsg" text= "Enter Your Email Address:" runat= "Server"/>
<form method= "POST" runat= "Server" >
Email recipient: <input type= "text" Name= "to" > <br>
Email Sender: <input type= "text" Name= "from" >
<input type= "Submit" name= "Submit" value= "Send Mail" runat= "Server" onserverclick= "SendMail" >
</FORM>
</BODY>

In the example above, the email address of the from (sender) and to (recipient) is collected from the corresponding text box, and the message is sent when the "Send Mail" button is clicked. When the Send Mail button is clicked, the form is passed back to itself, the "SendMail" (send mail) program is triggered on the server, and the message is sent. The following are examples of using C #:

<% @page language= "C #"%>
<% @Import namespace= "System.Web.Util"%>
<HTML><BODY>
<script language= "C #" runat= "Server" >
This are called on the server when the submit
The button is clicked on the client and the page
Posts back to itself
public void SendMail (Object Obj, EventArgs E)
{
Instantiate a MailMessage object. This serves as a message object
On which we can set properties.
MailMessage mailobj = new MailMessage ();
Set the "from" to "address" on the email
Mailobj.from = Request.Form ("from");
Mailobj.to = Request.Form ("to");
Mailobj.subject = "Subject of the Mail";
Mailobj.body = "Body of the Mail";
optional:html format for the email
Mailobj.bodyformat = mailformat.html;
Optional:encoding for the message
mailobj.bodyencoding = mailformat.base64;
Optional:set the priority of the
mailobj.priority = Mailpriority.high;
Optional:attach a file to the email.
Here we are have created a MailAttachment object to
Attach a file to the email
MAILOBJ.ATTACHMENTS.ADD (New MailAttachment ("C://test.doc"));
Send the email using the SmtpMail object
Smtpmail.send (Mailobj);
}
</SCRIPT>
<asp:label id= "headingmsg" text= "Enter Your Email Address:" runat= "Server"/>
<form method= "POST" runat= "Server" >
Email recipient: <input type= "text" Name= "to" > <br>
Email Sender: <input type= "text" Name= "from" >
<input type= "Submit" name= "Submit" value= "Send Mail" runat= "Server" onserverclick= "SendMail" >
</FORM>
</BODY>

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.