一些关于C#发送邮件的代码

时间:2022-04-18 00:57:32

SmtpClient smtp = new SmtpClient(); smtp.EnableSsl = false; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.163.com"; smtp.Credentials = new NetworkCredential("三角猫@163.com", "这是密码"); MailMessage mm = new MailMessage(); mm.From = new MailAddress("三角猫@163.com", "三角猫", Encoding.GetEncoding(936)); mm.To.Add("三角猫@gmail.com"); mm.SubjectEncoding = Encoding.GetEncoding(936); mm.Subject = "三角猫发的测试邮件,呵呵"; mm.BodyEncoding = Encoding.GetEncoding(936); ////普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的 string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容"; mm.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainTextBody, null, "text/plain")); ////HTML格式邮件的内容 string htmlBodyContent = "如果你的看到<b>这个</b>,, 说明你是在以 <span style=http://www.mamicode.com/\"color:red\">HTML</span> 格式查看邮件<br><br>"; htmlBodyContent += "<a href=http://www.mamicode.com/\"http://www.zu14.cn/\">真有意思网</a> <img src=http://www.mamicode.com/\"cid:weblogo\">"; //注意此处嵌入的图片资源 AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html"); ////处理嵌入图片 LinkedResource lrImage = new LinkedResource(@"d:\blogo.gif", "image/gif"); lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片 htmlBody.LinkedResources.Add(lrImage); mm.AlternateViews.Add(htmlBody); ////要求回执的标志 mm.Headers.Add("Disposition-Notification-To", "接收回执的邮箱@163.com"); ////自定义邮件头 mm.Headers.Add("X-Website", "http://www.zu14.cn/"); ////针对 LOTUS DOMINO SERVER,插入回执头 mm.Headers.Add("ReturnReceipt", "1"); mm.Priority = MailPriority.Normal; //优先级 mm.ReplyTo = new MailAddress("回复邮件的接收地址@yahoo.com.cn", "我自己", Encoding.GetEncoding(936)); ////如果发送失败,SMTP 服务器将发送 失败邮件告诉我 mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; ////异步发送完成时的处理事件 smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted); ////开始异步发送 smtp.SendAsync(mm, null);