In the namespace using System. Net. Mail, a method is provided to send emails Based on the specified smtp server. The following describes how to implement it:
1. First, you must send an email. You must have an email account, such as Netease mail, groom mail, and QQ mail. I will use Netease's 163 mailbox as an example. Then we need to know the smtp server address of the 163 mailbox: smtp.163.com. The common Smtp server address is:
Netease 126: smtp.126.com
Netease 163: smtp.163.com
Sohu: smtp.sohu.com
Sina: smtp.sina.com.cn
Yahoo!: smtp.mail.yahoo.com
2. Now we can start to implement it. In the newly created C # Console Application, you need to add two namespaces:
Using System. Net. Mail; // used to create and send emails
Using System. Net; // used to create an authenticated account
3. The function for sending emails is as follows:
Public static void SendEmail (
String userEmail, // sender's email
String userPswd, // password of the email account
String toEmail, // recipient's email address
String mailServer, // email server
String subject, // mail title
String mailBody, // email content
String [] attachFiles // email attachment
)
{
// Login Name of the email account
String username = userEmail. Substring (0, userEmail. IndexOf (@));
// Email sender
MailAddress from = new MailAddress (userEmail );
// Email recipient
MailAddress to = new MailAddress (toEmail );
MailMessage mailobj = new MailMessage (from, );
// Add sending and CC
// Mailobj. To. Add ("");
// Mailobj. CC. Add ("");
// Mail title
Mailobj. Subject = subject;
// Email content
Mailobj. Body = mailBody;
Foreach (string attach in attachFiles)
{
Mailobj. Attachments. Add (new Attachment (attach ));
}
// The email is not in html format.
Mailobj. IsBodyHtml = false;
// Email encoding format
Mailobj. BodyEncoding = System. Text. Encoding. GetEncoding ("GB2312 ");
// Mail priority
Mailobj. Priority = MailPriority. High;
// Initializes a new instance of the System. Net. Mail. SmtpClient class
// That sends e-mail by using the specified SMTP server.
SmtpClient smtp = new SmtpClient (mailServer );
// Or use:
// SmtpClient smtp = new SmtpClient ();
// Smtp. Host = mailServer;
// Do not use default creden to access the server
Smtp. usedefacrecredentials = false;
Smtp. Credentials = new NetworkCredential (username, userPswd );
// Use network to send to smtp Server
Smtp. DeliveryMethod = SmtpDeliveryMethod. Network;
Try
{
// Start sending emails
Smtp. Send (mailobj );
}
Catch (Exception e)
{
Console. WriteLine (e. Message );
Console. WriteLine (e. StackTrace );
}
}
4. Now, you can try to add the email sending function to your application.