繁体   English   中英

C# SmtpException - 发送邮件问题

[英]C# SmtpException - problem with sending mails

发送邮件不起作用。 我不确定它是否与客户端设置或邮件服务器有关...

使用 Gmail SMTP 服务器时出现“连接关闭”异常,将端口更改为 587 时出现“需要身份验证”消息。 将 SMTP 服务器更改为不同的服务器时更有趣的是( smtp.poczta.onet.pl )我在〜100秒后得到“超时”异常

这是代码:

protected void SendMessage(object sender, EventArgs e)
{
    // receiver address
    string to = "******@student.uj.edu.pl";

    // mail (sender) address
    string from = "******@gmail.com";

    // SMTP server address
    string server = "smtp.gmail.com";

    // mail password
    string password = "************";

    MailMessage message = new MailMessage(from, to);

    // message title
    message.Subject = TextBox1.Text;

    // message body
    message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;

    SmtpClient client = new SmtpClient(server, 587);
    client.Credentials = new System.Net.NetworkCredential(from, password);
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.EnableSsl = true;

    try
    {
        client.Send(message);

        // ui confirmation
        TextBox3.Text = "Wysłano wiadmość!";

        // disable button
        Button1.Enabled = false;
    }
    catch (Exception ex)
    {
        // error message
        TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
    }
}

我刚刚读到谷歌自 22 年 5 月 30 日起不支持一些不太安全的应用程序(第三方应用程序仅使用用户名和密码登录 Google 帐户)。 不幸的是无法更改它,因为我有两阶段验证帐户。 可能有关联吗? 还是我的代码有问题?

Gmail 不允许,或者希望您不再使用密码来执行此操作。 他们要求您创建凭证文件,然后使用 token.json 发送 email。

使用来自 Google.Apis.Gmail.v1 的Google.Apis.Gmail.v1 - 来自 Nuget。 这是我制作并测试的一种方法,它与 gmail 一起使用。

void Main()
{
    UserCredential credential;

    using (var stream =
        new FileStream(@"C:\credentials.json", FileMode.Open, FileAccess.Read))
    {
        // The file token.json stores the user's access and refresh tokens, and is created
        // automatically when the authorization flow completes for the first time.
        string credPath = "token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

    // Define parameters of request.
    UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

    // List labels.
    IList<Label> labels = request.Execute().Labels;
    Console.WriteLine("Labels:");
    if (labels != null && labels.Count > 0)
    {
        foreach (var labelItem in labels)
        {
            Console.WriteLine("{0}", labelItem.Name);
        }
    }
    else
    {
        Console.WriteLine("No labels found.");
    }
    //Console.Read();
    var msg = new Google.Apis.Gmail.v1.Data.Message();
    MimeMessage message = new MimeMessage();
    
    message.To.Add(new MailboxAddress("", "toemail.com"));
    message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere@gmail.com"));
    message.Subject = "Test email with Mime Message";
    message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
    
    var ms = new MemoryStream();
    message.WriteTo(ms);
    ms.Position = 0;
    StreamReader sr = new StreamReader(ms);
    string rawString = sr.ReadToEnd();

    byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
    msg.Raw = System.Convert.ToBase64String(raw);
    
    var res = service.Users.Messages.Send(msg, "me").Execute();
    
    res.Dump();


}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";

在您的 email 上启用 2FA 并使用链接为您的应用程序生成密码。 据我所知,谷歌不再支持使用未经授权的开发者程序进行登录和密码授权。

您可以从您的机器或部署代码的机器上 ping smpt 服务器吗? 这可能是 DNS 问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM