备注:需要引入两个命名空间
using System.Net.Mail;
using System.Net;
程序部分:
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();//退出程序
}
private void button3_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
G_Attachment.Text = openFileDialog1.FileName;//获取附件。
}
}
private void button1_Click(object sender, EventArgs e)
{
string MyPsd = G_password.Text;
string MyEmail = G_email.Text.Trim() + "@gmail.com";
MailMessage MMsg = new MailMessage();
MMsg.Subject = G_subject.Text.Trim();
MMsg.From = new MailAddress(MyEmail);
MMsg.To.Add(new MailAddress(G_address.Text.Trim()));
MMsg.IsBodyHtml = true;//这里启用IsBodyHtml是为了支持内容中的Html。
MMsg.BodyEncoding = Encoding.UTF8;//将正文的编码形式设置为UTF8。
MMsg.Body = G_content.Text;
SmtpClient SClient = new SmtpClient();
SClient.Host = "smtp.gmail.com";//google的smtp地址
SClient.Port = 587;//google的smtp端口
SClient.EnableSsl = true;//因为google使用了SSL(安全套接字层)加密链接所以这里的EnableSsl必须设置为true。
SClient.Credentials = new NetworkCredential(MyEmail, MyPsd);
if (G_Attachment.Text.Length>0)
{
MMsg.Attachments.Add(new Attachment(G_Attachment.Text));//判断是否有附件
}
try
{
SClient.Send(MMsg);
MessageBox.Show("邮件已经发送成功");
}
catch (Exception err)
{
MessageBox.Show(err.Message, "错误提示");
}
}
实例2:
string to = "get@tom.com";
string from = "set@tom.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client测试邮件.";
message.Body = @"测试邮件.";
SmtpClient client = new SmtpClient("smtp.tom.com",25);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.Credentials = new NetworkCredential("set@tom.com","****"); //指定发送的用户名,密码
client.Send(message);
MessageBox.Show("发送成功ok");