本文介绍了Gmail:如何以编程方式发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在尝试使用gmail发送电子邮件:

I'm trying to send an email using gmail:

我尝试过在本网站和其他网站上发现的各种示例,但我总是收到相同的错误:

无法连接到远程服务器 - > System.net .Sockets.SocketException:由于目标主动拒绝,不能建立连接209.85.147.109:587

I tried various examples that I found on this site and other sites but I always get the same error:
Unable to connect to the remote server -- > System.net.Sockets.SocketException: No connection could be made because the target actively refused it 209.85.147.109:587

    public static void Attempt1()
    {
        var client = new SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new NetworkCredential("[email protected]", "MyPassWord"),
            EnableSsl = true
        };
        client.Send("[email protected]", "[email protected]", "test", "testbody");
    }

任何想法?

更新

更多细节

也许我应该说什么其他尝试我给了我同样的错误:
(注意,当我没有指定端口,它尝试端口25)

Maybe I should say what other attempts I made that gave me the same error:(Note when i didn't specify a port it tryed port 25)

    public static void Attempt2()
    {
        var fromAddress = new MailAddress("[email protected]", "From Name");
        var toAddress = new MailAddress("[email protected]", "To Name");
        const string fromPassword = "pass";
        const string subject = "Subject";
        const string body = "Body";
        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        }
            ) { smtp.Send(message); }
    }


    public static void Attempt3()
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("[email protected]");
        mail.From = new MailAddress("[email protected]");
        mail.Subject = "Email using Gmail";

        string Body = "Hi, this mail is to test sending mail" +
                      "using Gmail in ASP.NET";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Credentials = new System.Net.NetworkCredential
             ("[email protected]", "pass");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }


推荐答案

我正在使用以下代码:

SmtpClient sc = new SmtpClient("smtp.gmail.com");
NetworkCredential nc = new NetworkCredential("username", "password");//username doesn't include @gmail.com
sc.UseDefaultCredentials = false;
sc.Credentials = nc;
sc.EnableSsl = true;
sc.Port = 587;
try {
    sc.Send(mm);
} catch (Exception ex) {
    EventLog.WriteEntry("Error Sending", EventLogEntryType.Error);
}

这篇关于Gmail:如何以编程方式发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:39