首页 > 解决方案 > Xamarin,使用 SmtpClient 发送邮件时出错

问题描述

我正在使用 System.Net.Mail.SmtpClient 在我的 Xamarin Form 应用程序中发送邮件。它设置为使用我的 gmail 地址,并且运行良好。

我想从 smtp 服务器(如果有)获取错误以通知用户。

所以,我正在使用事件 _SendCompleted

这是我的代码

(发送电子邮件)

 MailMessage mail = new MailMessage();
                        SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
                        
                        mail.From = new MailAddress(outils.emailEmetteur);
                        mail.To.Add("toto@outlook.frfr");//Tiers.contactEmail);
                        mail.Subject = outils.emailObjetDefaut;
                        mail.Body = outils.emailMessageDefaut;

                        bool fileExist = File.Exists(filePath);
                        if (fileExist)
                        {
                            Attachment pJ = new Attachment(filePath);
                            mail.Attachments.Add(pJ);

                            smtpServer.Port = 587;
                            smtpServer.Host = "smtp.gmail.com";
                            smtpServer.EnableSsl = true;
                            smtpServer.UseDefaultCredentials = false;
                            smtpServer.Credentials = new NetworkCredential(outils.emailEmetteur, outils.emailEmetteurMDP);

                            try
                            {
                                smtpServer.SendAsync(mail, null);
                                smtpServer.SendCompleted += smtpServer_SendCompleted;

                                return true;
                            }
                            catch (Exception ex)
                            {
                               
                            }
                        }

(发送完成的事件)

 private static void smtpServer_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            string token = (string)e.UserState;
            string info = "";

            if (e.Cancelled)
            {
                info = "Send canceled.";
            }
            if (e.Error != null)
            {
                info = e.Error.ToString();
            }
            else
            {
                info = "Message sent.";
            }
        }

我正在尝试向不正确的地址发送电子邮件 (toto@outlook.frfr)

我的事件被正确触发,但 e.Cancelled 和 e.Error 为 NULL,并且在我的 Gmail 收件箱中,我收到来自 smtp 服务器的错误,告诉我电子邮件地址不正确,以及我想在我的 Xamarin 中获得什么应用程序。

你有什么主意吗 ?谢谢 :)

标签: emailxamarinerror-handlingsmtpsmtpclient

解决方案


您的客户端将其中继到 Gmail 的外发邮件服务器;将消息提交到 SMTP 的事务成功。该错误仅在稍后发生,当 Gmail 尝试连接到收件人的邮件服务器但无法解决时;此时,您的客户端不再需要连接,因此邮件服务器会生成退回邮件并将其发送到发件人的收件箱。

在一般情况下,您要么必须编写自己的邮件服务器(但不,不要去那里)或检查收件箱中的退回邮件。


推荐阅读