A few days ago, students asked how to send e-mail in C #, a lot of online articles, conveniently found an article, to students, let him go to see. As a result, the day has not been fixed, had to look carefully. e-mail sent in C #, many articles on the internet are used smtpclient, there are System.Web.Mail, but System.Web.Mail is not recommended. The following is an e-mail message that is common on the Web:
1 MailMessage MyEmilMessage=new MailMessage();
2 string attachFile; //用于构造附件的字符串变量
3
4 MyEmailMessage.From="Writer@sadf.com";
5 MyEmailMessage.To="Geter@dff.com;tome@asd.com";
6 MyEmailMessage.Subject="邮件发送的一个简单例子";
7 MyEmailMessage.body="猫王呼叫耗子,收到请回答!!!";
8 MyEmailMessage.BodyFormat=MailFormat.Text;
9 MyEmailMessage.Priority=MailPriority.High;
10
11 //构造添加附件
12 attachFile=@"D:\test\test.txt";
13 MailAttachment mailAttach=new MailAttachment(attachFile);
14 MyEmailMessage.Attachments.Add(mailAttach);
15
16 //发送电子邮件
17 SmtpMail.SmtpServer="发送电子邮件的SMTP地址或者IP";// 指定smtp服务器
18 SmtpMail.Send(MyEmailMessage);//发送电子邮件
19
There is basically nothing wrong with the code, and compilation will pass, but if you send it in this way, you can basically guarantee that your email is not being sent successfully. Then, here is the lack of authentication, and the more troublesome is this authentication. Here's an example I wrote to my students:
1 String mailcontent= "message contents";
2 3 MailMessage msg = new System.Net.Mail.MailMessage (); 4 Msg. To.add ("Hu Jintao @gmail. com"); Recipient 5 6//Sender Information 7 MSG.
from = new MailAddress ("* * * @gmail. com", "sender name", System.Text.Encoding.UTF8); 8 Msg. Subject = "This is the test mail"; Message Title 9 Msg. subjectencoding = System.Text.Encoding.UTF8; The title encodes ten Msg. BODY = mailcontent; The main message is MSG.
bodyencoding = System.Text.Encoding.UTF8; Msg. Isbodyhtml = true; is HTML MSG. Priority = Mailpriority.high;
Priority SmtpClient client = new SmtpClient (); 16//Set Gmail mailbox and password to client.
Credentials = new System.Net.NetworkCredential ("Account @gmail.com", "password"); Client.
Port = 587; Client.
Host = "smtp.gmail.com"; Client.
Enablessl = true;
Object userState = msg; Try 23 {24 Client.
Send (msg);
MessageBox.Show ("sent successfully"); (Exception ex) {MessageBox.Show Ex.
Message, "Send mail Error");