如果用QQ邮箱测试需要在邮箱里面设置里面开启POP\SMTP协议。并用获取授权码输入到密码框。
添加引用
using System.Net.Mail;
using System.Net;
实例化:MailMessage mmsg = new MailMessage();
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/// <summary> /// 发送电子邮件 /// </summary> /// <param name="sendEmailAddress">发件人邮箱地址</param> /// <param name="sendEmailPwd">发件人邮箱密码\授权码</param> /// <param name="msgToEmail">收件人邮箱地址</param> /// <param name="title">邮箱标题</param> /// <param name="content">邮件内容</param> /// <param name="host">邮箱服务器</param> /// <returns></returns> public int SendEmail(string sendEmailAddress, string sendEmailPwd, string msgToEmail, string title, string content, string host) { //发件者邮箱地址 string fjrtxt = sendEmailAddress; //发件者邮箱密码 string mmtxt = sendEmailPwd; //主题 string zttxt = title; //内容 string nrtxt = content; string[] fasong = fjrtxt.Split('@'); //设置邮件协议 SmtpClient client = new SmtpClient(host); client.EnableSsl = true; client.UseDefaultCredentials = false; //通过网络发送到Smtp服务器 client.DeliveryMethod = SmtpDeliveryMethod.Network; //通过用户名和密码 认证 client.Credentials = new NetworkCredential(fasong[0].ToString(), mmtxt); //发件人和收件人的邮箱地址 // MailMessage mmsg = new MailMessage(); //表示电子邮件: MailMessage mmsg.From = new MailAddress(fjrtxt); //邮件地址 :MailAddress mmsg.To.Add(new MailAddress(msgToEmail)); //邮件主题 mmsg.Subject = zttxt; //主题编码 mmsg.SubjectEncoding = Encoding.UTF8; //邮件正文 mmsg.Body = nrtxt; //正文编码 mmsg.BodyEncoding = Encoding.UTF8; //设置为HTML格式 mmsg.IsBodyHtml = true; //优先级 mmsg.Priority = MailPriority.High; try { client.Send(mmsg); return 1; } catch { return 0; } }
上传附件
private void 上传附件button1_Click(object sender, EventArgs e) { // MailMessage mm = new MailMessage(); OpenFileDialog openFile = new OpenFileDialog(); if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { mmsg.Attachments.Add(new Attachment(openFile.FileName)); this.fujian.Text = openFile.FileName; } }
发送按钮
private void 发送button2_Click(object sender, EventArgs e) { int mesAge = SendEmail(fajianren.Text, mima.Text, shoujianren.Text, biaoti.Text, neirong.Text, "smtp.qq.com");//mima就是授权码 if (mesAge == 1) MessageBox.Show("发送成功!"); else MessageBox.Show("发送失败!"); }
有问题可以留言