C#邮件发送 批量发送邮件 发送邮件嵌入图片 添加附件

C#、类库、方法 专栏收录该内容
72 篇文章 0 订阅

一、邮件发送

public void Send()
        {
        	 MailMessage mail = new MailMessage();
        	  try
            {
            	 //设置邮件的标题
            	 mail.Subject ="悠哉WebService报告";
            	 mail.SubjectEncoding = System.Text.Encoding.UTF8;
            	   //设置邮件的发件人
            	    string SendEmail = ConfigurationManager.AppSettings["SendEmail"].ToString();
            	     MailAddress Addressfrom = new MailAddress(SendEmail, "uzai", System.Text.Encoding.UTF8); //邮件的发件人
            	    mail.From = Addressfrom;
            	      /*  这里这样写是因为可能发给多个联系人,每个地址用 , 号隔开
                     */
                     List<string> mailAddress = new List<string>();
                foreach (string address in mailAddress)
                {
                    if (address != string.Empty)
                    {
                        mail.To.Add(new MailAddress(address, address, System.Text.Encoding.UTF8));
                    }
                }
                  //设置邮件的内容
                mail.Body = mailContent;
                 //设置邮件的格式
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                 //mail.IsBodyHtml = true;
                   //设置邮件的发送级别
                mail.Priority = MailPriority.Normal;
                //发送通知
                   mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                     SmtpClient client = new SmtpClient();
                        //设置用于 SMTP 事务的主机的名称,填IP地址也可以了
                         client.Host = "smtp.gmail.com";
                          client.Port = 25;
                           client.Timeout = 9999;
                             client.UseDefaultCredentials = true;
                client.EnableSsl = true;
                 //邮箱登陆名和密码
                string EmailLogName = ConfigurationManager.AppSettings["EmailLogName"].ToString();
                string EmailLogPwd = ConfigurationManager.AppSettings["EmailLogPwd"].ToString();
                client.Credentials = new System.Net.NetworkCredential(EmailLogName, EmailLogPwd);
                  client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    //发送email
                client.Send(mail);
                 }
            catch (Exception)
            {
            	  //当邮件发送失败,发送异常时 使用备用方法调用备用邮箱发送
                SendBackUp();
                 }
            finally
            {
                mail.Dispose();
            }
        }
        public void SendBackUp()
        {
        	 MailMessage mail = new MailMessage();
        	  try
            {
            	 //设置邮件的标题
            	 mail.Subject ="悠哉WebService报告";
            	 mail.SubjectEncoding = System.Text.Encoding.UTF8;
            	   //设置邮件的发件人
            	    string SendEmail = ConfigurationManager.AppSettings["SendEmail"].ToString();
            	     MailAddress Addressfrom = new MailAddress(SendEmail, "uzai", System.Text.Encoding.UTF8); //邮件的发件人
            	    mail.From = Addressfrom;
            	      /*  这里这样写是因为可能发给多个联系人,每个地址用 , 号隔开
                     */
                     List<string> mailAddress = new List<string>();
                foreach (string address in mailAddress)
                {
                    if (address != string.Empty)
                    {
                        mail.To.Add(new MailAddress(address, address, System.Text.Encoding.UTF8));
                    }
                }
                  //设置邮件的内容
                mail.Body = mailContent;
                 //设置邮件的格式
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                 //mail.IsBodyHtml = true;
                   //设置邮件的发送级别
                mail.Priority = MailPriority.Normal;
                //发送通知
                   mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                     SmtpClient client = new SmtpClient();
                        //设置用于 SMTP 事务的主机的名称,填IP地址也可以了
                         client.Host = "smtp.gmail.com";
                          client.Port = 25;
                           client.Timeout = 9999;
                             client.UseDefaultCredentials = true;
                client.EnableSsl = true;
                 //邮箱登陆名和密码
                string EmailLogName = ConfigurationManager.AppSettings["EmailLogName"].ToString();
                string EmailLogPwd = ConfigurationManager.AppSettings["EmailLogPwd"].ToString();
                client.Credentials = new System.Net.NetworkCredential(EmailLogName, EmailLogPwd);
                  client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    //发送email
                client.Send(mail);
                 }
            catch (Exception)
            {
            	  //当邮件发送失败,发送异常时 使用备用方法调用备用邮箱发送
                Send();
                 }
            finally
            {
                mail.Dispose();
            }
        }

二、发送邮件图片,附件

     我们在发送邮件时,一般图片都是用网络路径,但有时如果接收方不可直接访问外网,就不能看到图片了,比如公司内部邮件,跟外界就没法交流图片。

     那么我们就来把图片嵌入邮件中;查看人就没有限制了。

     ①、以linked的方式,此方式在邮件中不会出现图片的附件

     邮件内容调用图片格式为:<img src=\"cid:Email001\">
     发送邮件的服务端代码为:

 System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();      
    mailMessage.From="发送者邮箱";      
    mailMessage.To.Add("收件人邮件列表");      
    mailMessage.CC.Add("抄送人邮件列表");      
    mailMessage.Subject = subject;      
    AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(content,null,"text/html");      
    LinkedResource lrImage = new LinkedResource("a.jpg","image/gif");      
    lrImage.ContentId = "Email001";      
    htmlBody.LinkedResources.Add(lrImage);      
    mailMessage.AlternateViews.Add(htmlBody);      
    SmtpClient.Send(mailMessage);     

 SmtpClient smtp = new SmtpClient();   
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;   
            smtp.Host = "smtp.163.com";   
            smtp.Credentials = new NetworkCredential("renzhijie1111", "**");   
  
            MailMessage mm = new MailMessage();   
            mm.From = new MailAddress("test@163.com", "test");   
            mm.To.Add("test2@163.com");   
  
            mm.Subject = "测试图片邮件";   
  
            string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容";   
            mm.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainTextBody, null, "text/plain"));   
  
            HTML格式邮件的内容   
            string htmlBodyContent = "如果你的看到<b>这个</b>, 说明你是在以 <span style=\"color:red\">HTML</span> 格式查看邮件<br><br>";   
            htmlBodyContent += "<a href=\"http://www.fenbi360.net粉笔编程网</a> <img src=\"cid:weblogo\">";   //注意此处嵌入的图片资源   
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html");   
  
              
            LinkedResource lrImage = new LinkedResource(@"d:\1.jpg", "image/gif");   
            lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片   
            htmlBody.LinkedResources.Add(lrImage);   
  
            mm.AlternateViews.Add(htmlBody);   
  
            要求回执的标志   
            mm.Headers.Add("Disposition-Notification-To", "test@163.com");   
  
            自定义邮件头   
            mm.Headers.Add("X-Website", "http://www.fenbi360.net");   
  
            针对 LOTUS DOMINO SERVER,插入回执头   
            mm.Headers.Add("ReturnReceipt", "1");   
  
            mm.Priority = MailPriority.Normal; //优先级   
            mm.ReplyTo = new MailAddress("test2@163.com", "我自己");   
  
            如果发送失败,SMTP 服务器将发送 失败邮件告诉我   
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;   
  
            异步发送完成时的处理事件   
            smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);   
  
            开始异步发送   
            smtp.SendAsync(mm, null);   
  
  
  
  
  
void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)   
        {   
            if (e.Cancelled)   
            {   
                MessageBox.Show("发送被取消");   
            }   
            else  
            {   
                if (e.Error == null)   
                {   
                    MessageBox.Show("发送成功");   
                }   
                else  
                {   
                    MessageBox.Show("发送失败: " + e.Error.Message);   
                }   
            }   
        }   

②、以邮件附件的方式,此方式图片当附件发送,并会显示在邮件内容中。

 string htmlBodyContent = "如果你的看到<b>这个</b>, 说明你是在以 <span style=\"color:red\">HTML</span> 格式查看邮件<br><br>";      
    htmlBodyContent += "<a href=\"testimg\"></a> <img src=\"cid:webimg\">";   //注意此处嵌入的图片资源      
             
    System.Net.Mail.Attachment att = new Attachment(@"E:\ttt.gif");      
    att.ContentId = "webimg";    


  

  • 4
    点赞
  • 1
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值