【C#工具类】发送邮件(带有图片和附件)

共享一个工具类,在C#中发送邮件,可以添加图片,附件,还有CC,多个CC等功能。

public class SendEmail
{
    public SendEmail()
    {
    }

    /// <summary>
    /// 发送Email
    /// </summary>
    /// <param name="Subject">标题</param>
    /// <param name="Body">内容</param>
    /// <param name="From">发件人</param>
    /// <param name="To">收件人</param>
    /// <param name="CC">抄送</param>
    /// <param name="MailServer">邮件服务器</param>
    /// <param name="FilePath">附件文件路径</param>
    /// <param name="FileName">附件文件名</param>
    /// <returns>发送情况</returns>
    //public static string Send(string Subject, string Body, string From, string To, string CC, string MailServer, string FilePath, string FileName)
    //{
    //    if (Subject.Trim() == "")
    //    {
    //        return "Email title can not be empty.";
    //    }

    //    if (Body.Trim() == "")
    //    {
    //        return "Email content can not be empty.";
    //    }

    //    if (From.Trim() == "")
    //    {
    //        return "Email sender's name can not be empty.";
    //    }

    //    if (To.Trim() == "")
    //    {
    //        return "Email receiver's name can not be empty.";
    //    }

    //    if (MailServer.Trim() == "")
    //    {
    //        return "Sending server address can not be empty.";
    //    }

    //    try
    //    {
    //        System.Web.Mail.MailMessage Mailmsg = new System.Web.Mail.MailMessage();
    //        Mailmsg.Subject = Subject;
    //        Mailmsg.Body = Body;
    //        Mailmsg.From = From;
    //        Mailmsg.To = To;
    //        if (CC.Trim() != "")
    //        {
    //            Mailmsg.Cc = CC;
    //        }
    //        if (FilePath.Trim() != "" && FileName.Trim() != "")
    //        {
    //            if (File.Exists(FilePath + FileName))
    //            {
    //                MailAttachment mailattachment = new MailAttachment(FilePath + FileName);
    //                Mailmsg.Attachments.Add(mailattachment);
    //            }
    //        }

    //        Mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
    //        Mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", ConfigurationManager.AppSettings["EmailAccount"].ToString().Trim());
    //        Mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", ConfigurationManager.AppSettings["EmailPassword"].ToString().Trim());

    //        SmtpMail.SmtpServer = MailServer;
    //        SmtpMail.Send(Mailmsg);
    //        if (FilePath.Trim() != "" && FileName.Trim() != "")
    //        {
    //            if (File.Exists(FilePath + FileName))
    //            {
    //                DeleteFile(FilePath + FileName);
    //            }
    //        }
    //        return "Sent successfully.";
    //    }
    //    catch (Exception ex)
    //    {
    //        Utility.WriteError(ex.Message);
    //        throw new Exception("Email sending error, please contact administrator.");
    //    }
    //}


    public static string SendMailByImageWithBCC(string Subject, string Body, string From, string To, string CC,string BCC, string FilePath, string FileName, string ImagePath)
    {
        if (Subject.Trim() == "")
        {
            return "Email title can not be empty.";
        }

        if (Body.Trim() == "")
        {
            return "Email content can not be empty.";
        }

        if (From.Trim() == "")
        {
            return "Email sender's name can not be empty.";
        }

        if (To.Trim() == "")
        {
            return "Email receiver's name can not be empty.";
        }


        try
        {
            System.Net.Mail.MailMessage Mailmsg = new System.Net.Mail.MailMessage();
            Mailmsg.Subject = Subject;
            Mailmsg.From = new MailAddress(From);
            Mailmsg.To.Add(new MailAddress(To));

            //string content = "如果您邮件客户端不支持HTML格式,请切换到“普通文本”视图,将看到此内容";
            //Mailmsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, "text/plain"));
            //Body += "<br /><img src=\"cid:weblogo\">";   //注意此处嵌入的图片资源
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
            //LinkedResource lrImage = new LinkedResource(ImagePath, "image/gif");
            //lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片
            //htmlBody.LinkedResources.Add(lrImage);
            Mailmsg.AlternateViews.Add(htmlBody);
            if (CC.Trim() != "")
            {
                Mailmsg.CC.Add(new MailAddress(CC));
            }
            if (BCC.Trim() != "")
            {
                Mailmsg.Bcc.Add(new MailAddress(BCC));
            }
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    Mailmsg.Attachments.Add(new Attachment(FilePath + FileName));
                }
            }
            string MailServer = ConfigurationManager.AppSettings["MailServer"].ToString().Trim();
            string usrName = ConfigurationManager.AppSettings["RequestEmail"].ToString().Trim();
            string passWord = ConfigurationManager.AppSettings["RequestPwd"].ToString().Trim();
            System.Net.Mail.SmtpClient smtp = new SmtpClient(MailServer);
            smtp.Credentials = new NetworkCredential(usrName, passWord);
            smtp.Send(Mailmsg);
            Mailmsg.Dispose();
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    DeleteFile(FilePath + FileName);
                }
            }
            return "Sent successfully.";
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }


    /// <summary>
    /// 发送带图片的Email
    /// </summary>
    /// <param name="Subject">主题</param>
    /// <param name="Body">主体</param>
    /// <param name="From">发件人</param>
    /// <param name="To">收件人</param>
    /// <param name="CC">抄送</param>
    /// <param name="MailServer">MailServer</param>
    /// <param name="FilePath">文件路径</param>
    /// <param name="FileName">文件名称</param>
    /// <param name="ImagePath">图片路径</param>
    /// <returns></returns>
    public static string SendMailByImage(string Subject, string Body, string From, string To, string CC, string FilePath, string FileName, string ImagePath)
    {
        if (Subject.Trim() == "")
        {
            return "Email title can not be empty.";
        }

        if (Body.Trim() == "")
        {
            return "Email content can not be empty.";
        }

        if (From.Trim() == "")
        {
            return "Email sender's name can not be empty.";
        }

        if (To.Trim() == "")
        {
            return "Email receiver's name can not be empty.";
        }


        try
        {
            System.Net.Mail.MailMessage Mailmsg = new System.Net.Mail.MailMessage();
            Mailmsg.Subject = Subject;
            Mailmsg.From = new MailAddress(From);
            Mailmsg.To.Add(new MailAddress(To));

            //string content = "如果您邮件客户端不支持HTML格式,请切换到“普通文本”视图,将看到此内容";
            //Mailmsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, "text/plain"));
            //Body += "<br /><img src=\"cid:weblogo\">";   //注意此处嵌入的图片资源
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
            //LinkedResource lrImage = new LinkedResource(ImagePath, "image/gif");
            //lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片
            //htmlBody.LinkedResources.Add(lrImage);
            Mailmsg.AlternateViews.Add(htmlBody);
            if (CC.Trim() != "")
            {
                Mailmsg.CC.Add(new MailAddress(CC));
            }
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    Mailmsg.Attachments.Add(new Attachment(FilePath + FileName));
                }
            }
            string MailServer = ConfigurationManager.AppSettings["MailServer"].ToString().Trim();
            string usrName = ConfigurationManager.AppSettings["RequestEmail"].ToString().Trim();
            string passWord = ConfigurationManager.AppSettings["RequestPwd"].ToString().Trim();
            System.Net.Mail.SmtpClient smtp = new SmtpClient(MailServer);
            smtp.Credentials = new NetworkCredential(usrName, passWord);
            smtp.Send(Mailmsg);
            Mailmsg.Dispose();
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    DeleteFile(FilePath + FileName);
                }
            }
            return "Sent successfully.";
        }
        catch (Exception ex)
        {            
            throw new Exception(ex.Message);
        }
    }



    public static string SendMailByImageWithMultCC(string Subject, string Body, string From, string To, string CC, string MailServer, string FilePath, string FileName, string ImagePath)
    {
        if (Subject.Trim() == "")
        {
            return "Email title can not be empty.";
        }

        if (Body.Trim() == "")
        {
            return "Email content can not be empty.";
        }

        if (From.Trim() == "")
        {
            return "Email sender's name can not be empty.";
        }

        if (To.Trim() == "")
        {
            return "Email receiver's name can not be empty.";
        }

        if (MailServer.Trim() == "")
        {
            return "Sending server address can not be empty.";
        }

        try
        {
            System.Net.Mail.MailMessage Mailmsg = new System.Net.Mail.MailMessage();
            Mailmsg.Subject = Subject;
            Mailmsg.From = new MailAddress(From);
            Mailmsg.To.Add(new MailAddress(To));

            string content = "如果您邮件客户端不支持HTML格式,请切换到“普通文本”视图,将看到此内容";
            Mailmsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(content, null, "text/plain"));
            Body += "<br /><img src=\"cid:weblogo\">";   //注意此处嵌入的图片资源
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(Body, null, "text/html");
            LinkedResource lrImage = new LinkedResource(ImagePath, "image/gif");
            lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片
            htmlBody.LinkedResources.Add(lrImage);
            Mailmsg.AlternateViews.Add(htmlBody);
            if (CC.Trim() != "")
            {
                if (CC.IndexOf(";") == -1)
                {
                    Mailmsg.CC.Add(new MailAddress(CC));
                }
                else
                {
                    string[] ccList = CC.Split(';');
                    for (int i = 0; i < ccList.Length; i++)
                    {
                        Mailmsg.CC.Add(new MailAddress(ccList[i].ToString().Trim()));
                    }
                }
            }
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    Mailmsg.Attachments.Add(new Attachment(FilePath + FileName));
                }
            }
            string usrName = ConfigurationManager.AppSettings["EmailAccount"].ToString().Trim();
            string passWord = ConfigurationManager.AppSettings["EmailPassword"].ToString().Trim();
            System.Net.Mail.SmtpClient smtp = new SmtpClient(MailServer);
            smtp.Credentials = new NetworkCredential(usrName, passWord);
            smtp.Send(Mailmsg);
            Mailmsg.Dispose();
            if (FilePath.Trim() != "" && FileName.Trim() != "")
            {
                if (File.Exists(FilePath + FileName))
                {
                    DeleteFile(FilePath + FileName);
                }
            }
            return "Sent successfully.";
        }
        catch (Exception ex)
        {            
            throw new Exception(ex.Message);
        }
    }



    public static void DeleteFile(string Path)
    {
        if (File.Exists(Path))
        {
            File.Delete(Path);
        }
    }


}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值