您的位置:首页 > 编程语言 > C#

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

2011-10-19 22:48 399 查看
前段时间学习了一下,如何利用C#和Gmail帐号发送邮件。现在写下来来共享一下:

它的界面是这样的:

View Code

private void sendMailBtn_Click(object sender, EventArgs e)
{
pbSendEmail.Value = 0;
pbSendEmail.Maximum = 100;
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");

//mail from
mail.From = new MailAddress("123@gmail.com");

//mail to
if (string.IsNullOrEmpty(tbMailTo.Text))
{
MessageBox.Show("The recipient of this mail can‘t be empty!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
sendMailBtn.Enabled = false;
return;
}
string mailAddress = tbMailTo.Text.TrimEnd();
string[] mailAddresses = mailAddress.Split(',');
mailAddress = string.Empty;
ArrayList emailList = new ArrayList();
foreach(string address in mailAddresses)
{
string tempEmailAddress = address.Trim();
if (string.IsNullOrEmpty(tempEmailAddress))
{
continue;
}
if (!CheckEmail.IsEmail(tempEmailAddress))
{
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);
return;
}

emailList.Add(tempEmailAddress);

}
foreach (string tempEmailAddress in emailList)
{
mail.To.Add(tempEmailAddress);
pbSendEmail.Value++;
}

//mail subject
mail.Subject = tbSubject.Text.ToString();

//mail body
if (cbBodyFormat.SelectedText == "Text")
{
mail.IsBodyHtml = false;
}
else
{
mail.IsBodyHtml = true;
}
mail.BodyEncoding = Encoding.UTF8;
mail.Body = rtbMailBody.Text.ToString();

//mail attachment
if (!string.IsNullOrEmpty(tbAttachment.Text.ToString()))
{

System.Net.Mail.Attachment attachment = new Attachment(tbAttachment.Text);
mail.Attachments.Add(attachment);
}

//mail priority
if (cbMailPriority.SelectedText.ToString() == "High")
{
mail.Priority = MailPriority.High;
}
else if (cbMailPriority.SelectedText.ToString() == "Low")
{
mail.Priority = MailPriority.Low;
}
else
{
mail.Priority = MailPriority.Normal;
}

smtpServer.Port = 587;
smtpServer.Credentials = new System.Net.NetworkCredential("123", "password");
smtpServer.EnableSsl = true;

smtpServer.Send(mail);
pbSendEmail.Value = 100;
MessageBox.Show("Your mail has been sent successfully, please check it!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
catch (Exception ex)
{
MessageBox.Show("The following exception occurred: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: