C# 发送邮件的记录(qq,126,Gmail)

需求:用C#做一个发送邮件的接口。 
说明: 
1.smtp

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过SMTP协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。SMTP服务器则是遵循SMTP协议的发送邮件服务器,用来发送或中转发出的电子邮件。 
这是原理说明(蒙蔽,有时间再研究下) 
http://blog.csdn.net/kerry0071/article/details/28604267

2.smtp服务器地址和端口

25:如果不启用SSL认证,一般是这个端口; 
587/465:启动SSL认证。 
以下是常用邮箱的端口: 
http://blog.csdn.net/whyhonest/article/details/7289420 
QQ:smtp.qq.com:465 
126:smtp.126.com:25 
Gmail:smtp.gmail.com:587

步骤: 
1.先启动邮箱smtp功能:

QQ(126类似)–这两个要启用SSL都需要专门的授权码,可以在邮箱通过账号获取。 
http://jingyan.baidu.com/article/0f5fb099dffe7c6d8334ea31.html 
Gmail: 
需要fan墙,操作类似;除了在邮箱页面进行设置之外,还需要在客户端进行设置。(win10 用OutLook比较方便) 
参考:http://www.xujiahua.com/848.html 
官方:https://support.google.com/mail/answer/7126229?visit_id=1-636278354684802140-826274024&hl=zh-Hans&rd=1

2.编码部分:在C#中QQ 和 126/Gmail 所用类库不一样。QQ用System.Web.Mail;126用System.Net.Mail(QQ用会出操作超时的异常)。 
QQ

public static void SendQQEmailtest(string server, int port, string sender, string recipient, string subject, string body, bool isBodyHtml, Encoding encoding, string authentication, string userName, params string[] files)
        {
            System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
            mail.To = recipient;
            mail.From = sender;
            mail.Subject = subject;
            mail.BodyFormat = System.Web.Mail.MailFormat.Text;
            mail.Body = body;
            //添加附件
            mail.Attachments.Clear();
            if (files != null && files.Length != 0)
            {
                for (int i = 0; i < files.Length; ++i)
                {
                    Attachment attach = new Attachment(files[i]);
                    mail.Attachments.Add(attach);
                }
            }

            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", authentication); //这个密码要注意:如果是一般账号,要用授权码;企业账号用登录密码  

            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //身份验证  
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", mail.From); //邮箱登录账号,这里跟前面的发送账号一样就行  

            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port);//端口  
            mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//SSL加密  

            System.Web.Mail.SmtpMail.SmtpServer = server;    //企业账号用smtp.exmail.qq.com  
            System.Web.Mail.SmtpMail.Send(mail);  
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Gmail/126

public static void Send2test(string server, int port, string sender, string recipient, string subject,
    string body, bool isBodyHtml, Encoding encoding, string authentication, string userName, params string[] files)
        {
            //确定发件人地址、收件人地址
            MailMessage message = new MailMessage(sender, recipient);
            message.IsBodyHtml = isBodyHtml;

            message.SubjectEncoding = encoding;
            message.BodyEncoding = encoding;

            message.Subject = subject;
            message.Body = body;

            message.Attachments.Clear();
            if (files != null && files.Length != 0)
            {
                for (int i = 0; i < files.Length; ++i)
                {
                    Attachment attach = new Attachment(files[i]);
                    message.Attachments.Add(attach);
                }
            }

            //根据 邮件服务器 地址建立客户端
            SmtpClient smtpClient = new SmtpClient(server, port);//如果不写端口就会出现异常:AUTH fist!
            smtpClient.Timeout = 50000;
            smtpClient.EnableSsl = true;//从抓包的情况来看是有STARTTLS的

            if (string.IsNullOrEmpty(authentication))
            {
                smtpClient.UseDefaultCredentials = true;
            }
            else
            {
                //smtpClient.UseDefaultCredentials = true;//看来这句是可有可无的
                smtpClient.Credentials = new NetworkCredential(userName,
                    authentication);
            }
            //smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//通过网络发送
            try
            {
                smtpClient.Send(message);
            }
            catch (Exception ex)
            {

            }
            finally{
                smtpClient.Dispose();
            }

        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
有意思的是在Gmail中:smtpClient.UseDefaultCredentials = true 在官方的解释中: 
如果 UseDefaultCredentials 属性设置为 false,则连接到服务器时会将 Credentials 属性中设置的值用作凭据。 如果 UseDefaultCredentials 属性设置为 false并且尚未设置 Credentials 属性,则将邮件以匿名方式发送到服务器。 
然而调试中会出异常: 
其他信息: SMTP 服务器要求安全连接或客户端未通过身份验证。 服务器响应为:5.5.1 Authentication Required. 
当注释掉smtpClient.UseDefaultCredentials这句后,就能发送邮件了。

PS:关于其中遇到的问题及解决: 
1.126

不允许使用邮箱名称。 服务器响应为:authentication is required,126 smtp4, 
原因: 
输入了地址,但是port没有明确|没有输入验证信息 
-所以输入对应的port + 确认验证信息

2.关于Gmail这个大坑

1.调试中是否需要翻墙: 
否;否则在连接服务器的时候会出现各种失败; 
2.Gmail端口 
587而非465!否则会报操作超时; 
3.Gmail-tls 
在C#中,smtpClient.EnableSsl = true;相当于启用了tls,从wireshark中可以看出STARTTLS。不用花心思去琢磨用C#实现tls。以下是原理: 
4.是否需要修改Hosts 
参考:http://www.williamlong.info/archives/4455.html 
发现其中关于修改是针对OutLook的。我在实际操作中是修改了Hosts之后操作的OutLook,并且在该环境中进行调试并发送邮件成功的。但是会存在不稳定的问题,有时候会显示操作超时,但是邮件仍然收不到的情况; 
待还原Hosts文件后再测试下效果。 
5.Gmail有可能要设置“允许不够安全的应用访问”

参考文章:

http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000 
于是我坚定了从587端口尝试的决心 %>_<%,不过看起来Python好方便啊。465端口在尝试中发现与服务器连接各种失败、操作超时。 
http://stackoverflow.com/questions/2057227/c-sharp-asp-net-send-email-via-tls 
于是我放弃了琢磨TLS 
http://qa.helplib.com/198009 
于是我开始怀疑官方文档。。并且这里的答案是可信的。而且经过尝试,smtpClient.UseDefaultCredentials 可以不用管它。

2017年4月24日 更新 
后来为了解决System.web.mail过时方法的警告,采用了另外的解决方案。

http://www.codingwhy.com/view/614.html

public static void Send(string server, int port, string sender, string password, string recipient, string subject, string body, bool isBodyHtml, params string[] files)
        {
            CDO.Message objMail = new CDO.Message();
            try
            {
                objMail.To = recipient;
                objMail.From = sender;
                objMail.Subject = subject;//邮件主题string strHTML = @"";
                if (isBodyHtml == true)
                {
                    //strHTML = strHTML + "这里可以填写html内容";
                    objMail.HTMLBody = body;//邮件内容
                }
                else
                {
                    objMail.TextBody = body;
                }
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = port;//设置端口
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = server;
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = sender;//"发送邮件账号";
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = sender;//"发送邮件账号";
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = sender;//"发送邮件账号";
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = sender;//"发送邮件账号";
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = password;//"发送邮件账号登录密码";
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1;
                objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = "true";//这一句指示是否使用ssl
                if (files != null && files.Length != 0)
                {
                    for (int i = 0; i < files.Length; ++i)
                    {
                        objMail.AddAttachment(files[i], "", "");//"C:\\Hello.txt"
                    }
                }
                objMail.Configuration.Fields.Update();
                objMail.Send();
            }
            catch (Exception ex) { throw ex; }
            finally { objMail = null; }
        }

原文:https://blog.csdn.net/u013244192/article/details/70194595 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值