关山明月

导航

如何利用C#和Gmail帐号发送邮件

      前段时间学习了一下,如何利用C#和Gmail帐号发送邮件。现在写下来来共享一下:

      它的界面是这样的:      

      

       它的主要代码是这样的,当然先要添加System.Net.Mail命名空间。

View Code
  1         private void sendMailBtn_Click(object sender, EventArgs e)
2 {
3 pbSendEmail.Value = 0;
4 pbSendEmail.Maximum = 100;
5 try
6 {
7 MailMessage mail = new MailMessage();
8 SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
9
10
11 //mail from
12 mail.From = new MailAddress("123@gmail.com");
13
14 //mail to
15 if (string.IsNullOrEmpty(tbMailTo.Text))
16 {
17 MessageBox.Show("The recipient of this mail can‘t be empty!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
18 sendMailBtn.Enabled = false;
19 return;
20 }
21 string mailAddress = tbMailTo.Text.TrimEnd();
22 string[] mailAddresses = mailAddress.Split(',');
23 mailAddress = string.Empty;
24 ArrayList emailList = new ArrayList();
25 foreach(string address in mailAddresses)
26 {
27 string tempEmailAddress = address.Trim();
28 if (string.IsNullOrEmpty(tempEmailAddress))
29 {
30 continue;
31 }
32 if (!CheckEmail.IsEmail(tempEmailAddress))
33 {
34 MessageBox.Show("Invalid E-mail address: " + address + "\nIf there are multiple e-mail addresses, please seperate each of them by comma character.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
35 return;
36 }
37
38 emailList.Add(tempEmailAddress);
39
40 }
41 foreach (string tempEmailAddress in emailList)
42 {
43 mail.To.Add(tempEmailAddress);
44 pbSendEmail.Value++;
45 }
46
47 //mail subject
48 mail.Subject = tbSubject.Text.ToString();
49
50 //mail body
51 if (cbBodyFormat.SelectedText == "Text")
52 {
53 mail.IsBodyHtml = false;
54 }
55 else
56 {
57 mail.IsBodyHtml = true;
58 }
59 mail.BodyEncoding = Encoding.UTF8;
60 mail.Body = rtbMailBody.Text.ToString();
61
62 //mail attachment
63 if (!string.IsNullOrEmpty(tbAttachment.Text.ToString()))
64 {
65
66 System.Net.Mail.Attachment attachment = new Attachment(tbAttachment.Text);
67 mail.Attachments.Add(attachment);
68 }
69
70 //mail priority
71 if (cbMailPriority.SelectedText.ToString() == "High")
72 {
73 mail.Priority = MailPriority.High;
74 }
75 else if (cbMailPriority.SelectedText.ToString() == "Low")
76 {
77 mail.Priority = MailPriority.Low;
78 }
79 else
80 {
81 mail.Priority = MailPriority.Normal;
82 }
83
84 smtpServer.Port = 587;
85 smtpServer.Credentials = new System.Net.NetworkCredential("123", "password");
86 smtpServer.EnableSsl = true;
87
88 smtpServer.Send(mail);
89 pbSendEmail.Value = 100;
90 MessageBox.Show("Your mail has been sent successfully, please check it!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
91
92 }
93 catch (Exception ex)
94 {
95 MessageBox.Show("The following exception occurred: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
96 }
97 finally
98 {
99
100 }
101 }

 

posted on 2011-10-19 22:48  关山明月  阅读(274)  评论(0编辑  收藏  举报