In the second article of the mail series, this article describes how to use mailmessage and smtpclient in the namespace system. net. Mail to send emails.
Using system;
Using system. collections;
Using system. text;
Using system. net;
Using system. net. mail;
Namespace netmailsend
{
Class programe
{
Public static void main (string [] ARGs)
{
// Mail message
Mailmessage mymail = new mailmessage ();
Mymail. From = new mailaddress ("test@gmail.com ");
Mymail. to. Add (New mailaddress ("test@gmail.com "));
Mymail. Subject = "test ";
Mymail. subjectencoding = encoding. utf8;
Mymail. Body = "you are successed .";
Mymail. bodyencoding = encoding. utf8;
Mymail. isbodyhtml = false;
Mymail. Priority = mailpriority. High;
Mymail. CC. Add (New mailaddress ("test@gmail.com "));
Mymail. bcc. Add (New mailaddress ("test@gmail.com "));
// SMTP client
Smtpclient sender = new smtpclient ();
Sender. Host = "smtp.gmail.com ";
Sender. Port = 587;
Sender. Credentials = new networkcredential ("test@gmail.com", "test ");
Sender. deliverymethod = smtpdeliverymethod. Network;
Sender. enablessl = true;
Try
{
Sender. Send (mymail );
Console. writeline ("success ");
}
Catch (exception E)
{
Console. writeline ("failed. Exception: {0}", E. Message );
}
Console. Write ("press any key to quit ...");
Console. readkey ();
}
}
}
Pay attention to the following issues in this implementation:
- System. net. mail is. recommended Methods in Versions later than NET 2.0. It solves some encoding and security verification problems, and overwrites the mailmessage class, providing more functions, this makes it easier to create mailmessage.
- In system. net. Mail. mailmessage, The subjectencoding attribute is added, and methods in some domains are added for to, CC, and bcc to facilitate mass mailing. In addition, a more object-oriented mailaddress class object is used to indicate the mail address.
- The smtpclient class is added to system. net. Mail, which contains methods and attributes in this application, and can mark secure links.
- It is worth noting that SMTP (simple message transfer protocol) uses port 25, which is also provided by most mail service periods, but Gmail is different, gmail's latest port is 587, instead of the previous 465.
- Gmail servers require secure connections, so you must specify sender. enablessl = true.
- In addition, the smtpclient object has a very important method, which should be described as sendasync (). This method has been reloaded. Public void sendasync (mailmessage message, object usertoken) you must use mailmessage as the sending object and use usertoken to specify the method called during asynchronous operations. Public void sendasync (string from, string recipients, string subject, string body, object usertoken) can send emails directly without creating a mailmessage object. usertoken is the same as the previous function, public void sendasynccancel () cancels asynchronous operations to send emails.