发送电子邮件时出错.web.httpexceptions:无法将消息发送到smtp服务器

时间:2012-04-06 21:59:20

标签: c# email smtp

我的程序中有一个功能,可以从Google帐户发送电子邮件。

我曾经写过这段代码并且以前工作正常,它会发送电子邮件,就像它应该的那样。然而,现在,我无法让它发挥作用。 (我现在正在使用Windows 7 64位,如果这会产生影响)。

我得到的错误(这是代码中的第一条错误消息)是:

  

system.web.httpexceptions:无法将消息发送到smtp   服务器。传输错误代码是0x80040217。服务器响应   不可用 - > system.reflection.targetinvocationexception:   调用目标抛出了异常。 - >   system.runtime.interopservice.comexception(0x80040211):消息   无法发送到smtp服务器。传输错误代码是   0x80040217。服务器响应不可用。

这是代码:

void sendEmail(string [] emailList, int emailLength, string fileName)
{
    int i = 0;      //variable to act as temporary index into emailList array
    try
    {
        try
        {
            MailMessage message = new MailMessage();
        //Because using google server, requires SSL
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1 );
            message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername","theusername@gmail.com" );
            message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword","thepassword" );

            message.From = "theusername@gmail.com";
            message.To = emailList[i];

            //add Bcc
            while (++i < emailLength)
            {
                message.Bcc = emailList[i];
            }//end while

            message.Subject = "Test Subject";
            message.Body = "Test Body";

            MailAttachment fileAttach = new MailAttachment(fileName);
            message.Attachments.Add(fileAttach);

            try
            {       
                SmtpMail.SmtpServer = "smtp.gmail.com";

提前谢谢!

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,但是当我使用Gmail地址时我没有使用Gmail登录的两步验证解决了这个问题。如果您只使用密码而没有额外的验证(在我的情况下通过手机代码),它可以正常工作

答案 1 :(得分:1)

也许你被Google封锁了,因为你是从远程计算机中的程序发送的(这不是你通常使用的程序) 尝试在运行该程序的同一台计算机上打开gmail。看看你是否有安全问题。

在gmail帐户上

转到https://www.google.com/settings/account然后打开安全设备,看到我的Gmail已阻止访问您的帐户