第一次发表文章,也是我第一个使用C#编写的程序,现在分享出来,希望前辈点评一下。
对于.net 2.0之前的技术中,微软提供了一个命名空间为System.Web.Mail的一系列类和方法,首先,写出使用这个命名空间提供的MailMessage和SmtpMail两个类实现邮件发送的功能。
using System;
using System.Collections;
using System.Text;
using System.Web.Mail;
namespace WebMailSend
{
class Programe
{
//some const string to show the mail infomation
//accout info would be replaced.
private const string mailFrom = "[email protected]";
private const string mailTo = "[email protected]";
private const string mailSubject = "Just a test Mail";
//some const string to create the smtp server and user
private const string sendServer = "stmp.gmail.com";
private const string sendUsr = "[email protected]";
private const string sendPwd = "######";
public static void Main(string[] args)
{
//create a mail to send
MailMessage myMail = new MailMessage();
myMail.From = mailFrom;//email from
myMail.To = mailTo;//email to: reciever's email address
myMail.Subject = mailSubject;//the email's subject
myMail.Body = "You are really success.";//the email's body
myMail.BodyEncoding = Encoding.UTF8;//the coding, in windows, usually is utf-8
myMail.BodyFormat = MailFormat.Text;//the body format html or text;
//myMail.Cc = ""; //
//myMail.Bcc = "";
//myMail.Priority = MailPriority.High | MailPriority.Low | MailPriority.Normal;
//set the mail to be certify needed
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
//set the user to be certified
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusername", sendUsr);
//the password of the account
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtppassword",sendPwd);
SmtpMail.SmtpServer = sendServer;
try
{
SmtpMail.Send(myMail);
}
catch (Exception e)
{
Console.WriteLine("Exception throw out:{0}", e.Message);
}
Console.WriteLine("Press any key to quit...");
Console.ReadKey();
}
}
}
对于这个程序中有一些要注意的地方:
1.第一个要提出的就是关于myMail.BodyEncoding = Encoding.UTF8的问题,一般来讲windows系统中的邮件使用的都是这个编码方式,如果采用其它的方式有可能会出现邮件发送后变成乱码的现象;
2.再一个就是myMail.Fields的使用,其中添加了三个域。分别是标注邮箱为用户验证,邮箱账户名,邮箱密码三个属性。myMail.Fields.Add(object key, object value)是继承自System.Collections.IDictionay.Add(object key, object value)的方法,对于本程序,三个cdo.message的都是固定的,分别标注三种属性,后面是对该属性所赋予的值。
3.还有一个问题就是大家将会碰到的,现在市面上的主流邮箱很多已经不是默认支持外部程序调用smtp邮件发送的,从而在执行程序时会产生很多异常,而且都是乱码,不用担心,这并不是程序的问题,而是System.Web.Mail的问题,这些异常当改用System.Net.Mail的时候就会被用中文标记出来。举例:163,sina,126都是不可用的。
4.最后要提到的,该方法已经过时,System.Web.Mail类已经过时,其smtp服务期有很多属性不能指定,包括端口,安全验证等等,已经逐步被System.Net.Mail所替代。
转载于:https://www.cnblogs.com/apollohan/archive/2009/02/21/SendMails.html