C#实现发送QQ邮件并添加附件

之前在公司遇到一个需求需要发送邮件并需要添加附件,我当时用了QQ的SMTP实现了发送邮件的功能。现在记录一下。并做了简单的封装。有不对的地方,请大家多多包涵,一起交流学习

一、准备工作,
要使用SMTP发送邮件,首先需要去QQ的邮箱配置。步骤如下
1、打开QQ邮箱
2、点击设置
在这里插入图片描述
3、点击账户
在这里插入图片描述
4、开启下图这两个服务,并拿到授权码,之后发送邮件的地方需要。
在这里插入图片描述

代码如下,已做了简单的封装

下面的邮件信息,我没有直接写在发送代码中,而是写在了配置文件web.config中,这样的好处是:在以后的维护中,需要修改邮件信息的话,直接修改配置文件就行,不用修改代码了,

  //配置文件web.config
 <add key="MailSMTPServer" value="smtp.qq.com" />//SMTP主机域
 <add key="MailSMTPPort" value="25" />// 发送邮件的端口
 <add key="MailSender" value="" />//value填写你的QQ邮件
 <add key="MailSenderPwd" value="" />//value填写你的邮件的授权码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Configuration;

namespace EmailSend
{
 public  class EmailSender
    {
       //读取上面配置文件中的信息
        string strMeEmail = ConfigurationManager.AppSettings.Get("MailSender");//邮件来自该邮件
        string strPWD = ConfigurationManager.AppSettings.Get("MailSenderPwd");   //该邮件授权码
        string strServer = ConfigurationManager.AppSettings.Get("MailSMTPServer"); //SMTP主机域
        int strPort = Convert.ToInt32(ConfigurationManager.AppSettings.Get("MailSMTPPort")); //SMTP端口
        MailMessage mailMsg;
        SmtpClient smtpClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="strsubject">邮件主题</param>
        /// <param name="strto">收件人</param>
        /// <param name="strcontent">邮件内容</param>
        public EmailSender(string strsubject,string strto,string strcontent)
        {
            mailMsg = new MailMessage(strMeEmail, strto);
            mailMsg.Subject = strsubject;
            mailMsg.SubjectEncoding = Encoding.UTF8;
            mailMsg.Priority = MailPriority.Normal;
            mailMsg.IsBodyHtml = true;//如果你的邮件内容需要拼接HTML的话,改属性设置为true
            mailMsg.Body = strcontent;
            mailMsg.BodyEncoding = Encoding.UTF8;
        }

        /// <summary>
        /// 增加附件
        /// </summary>
        /// <param name="path">附件路径</param>
        public void AddAttchment(string path)
        {  try
            {
                Attachment attachMent;
                attachMent = new Attachment(path);
                mailMsg.Attachments.Add(attachMent);
            }
            catch(Exception ex)
            {
                 throw new Exception(ex.Message);
            }
                      
        }


        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <returns>是否发送成功</returns>
        public bool SendEmail()
        {
            smtpClient = new SmtpClient(strServer,strPort);
            smtpClient.UseDefaultCredentials = false;                           //是否使用默认身份验证(如果你的SMTP不需要身份验证,可以设置此项为TRUE,否则就为false),为false时,就需要身份验证,使用下面的Credentials
            smtpClient.EnableSsl=true;                                          //是否加密链接,这里必须设置为true,否则无法发送邮件
            smtpClient.DeliveryMethod= SmtpDeliveryMethod.Network;              //指定发送邮件的方法,以网络的形式
            smtpClient.Timeout=15000;
            smtpClient.Credentials = new NetworkCredential(strMeEmail,strPWD);  //设置链接SMTP时的身份验证,也就是我要连接的QQ邮箱的服务器,我需要我邮箱的密码,才可以用它发送邮件,而且必须开通了QQ的SMTP服务,使用生成的凭证码
            try
            {
                smtpClient.Send(mailMsg);
                return true;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    }
}

调用
因为我的邮件内容是用html拼接的,所以是这样的,如果你不需要的话,就把 IsBodyHtml 设置为false,然后合同内容直接写就行。

 StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.Append("<!DOCTYPE html>");
                        stringBuilder.Append("<html>");
                        stringBuilder.Append("<head>");
                        stringBuilder.Append("<meta charset="+"{CHARSET}"+">");
                        stringBuilder.Append("<title></title>");
                        stringBuilder.Append("</head>");
                        stringBuilder.Append("<body>");
                        stringBuilder.Append("<div style="+"width: 500px; "+">");
                        stringBuilder.Append($"<h3>尊敬的XX先生/</h3>")
                        stringBuilder.Append("<br />");
                        stringBuilder.Append("<div style=" + "float: right; " + ">");                       
                        stringBuilder.Append("</div>");
                        stringBuilder.Append("</div>");
                        stringBuilder.Append("</body>");
                        stringBuilder.Append("</html>");
      //DirectorEmail 是对方的邮件
   EmailSender email = new EmailSender("你好", DirectorEmail, stringBuilder.ToString());
                        LogHelper.Info("DirectorEmail", "文件地址:" + ConlocalPath);
                        //path 是附件地址
                        email.AddAttchment(Path);
                        email.SendEmail();
                       

注意:
1、因为QQ邮箱的SMTP使用了SSL加密,所以EnableSsl必须设置为true ,否则发送不出去.
2、增加附件的地方,给上文件的地址,比如这样添加附件
email.AddAttchment(@“C:\Users\Administrator\Downloads\图片\1.svg”);
3、发布到服务器上的时候,以华为云服务器为例,华为云服务器默认是关闭了25端口的,如果要使用25端口的话,要在华为云提交工单申请打开25端口 。

有问题请联系我,我看到了都会回复。谢谢大家。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书语时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值