使用 C# 发送电子邮件 - 不起作用,但没有抛出错误

Dav*_*ave 2 c# asp.net smtp smtpclient

正如主题标题所暗示的那样,我正在尝试从我的 C# 应用程序发送电子邮件,但遇到了一些麻烦。

我编写了下面的函数,以便更轻松地从我的应用程序发送邮件,但我相信某处一定有问题,我只是看不到它。也许这是“只见树木不见森林”的情景。

当我尝试通过 SMTP 发送电子邮件时会出现问题。该页面似乎超时,根本没有错误消息.. LocalPickup 工作,指定拾取目录也是如此,但在这种情况下,我需要使用 SMTP。

在这种情况下,我的网站位于我的家庭开发服务器(运行 windows server 2003)上,而我的 SMTP 服务器是一个运行 CentOS Linux 和 Qmail 的远程专用机器。

我已经包含了我写的函数,只是为了回答任何问题..是的,这台服务器上的 SMTP 端口肯定是 26 ;)

    /// <summary>
    /// Sends an email
    /// </summary>
    /// <param name="To">Addresses to send the email to, comma seperated</param>
    /// <param name="subject">Subject of the email</param>
    /// <param name="emailBody">Content of the email</param>
    /// <param name="cc">CC addresses, comma seperated [Optional]</param>
    /// <param name="Bcc">BCC addresses, comma seperated [Optional]</param>
    /// <param name="client">How to send mail, choices: iis, network, directory. [Optional] Defaults to iis</param>
    /// <returns></returns>
    public bool sendMail(string To, string subject, string emailBody, string from, string cc = "", string Bcc = "", string client = "network", bool html = true)
    {

        // Create a mailMessage object
        MailMessage objEmail = new MailMessage();
        objEmail.From = new MailAddress(from);
        // Split email addresses by comma
        string[] emailTo = To.Split(',');
        foreach (string address in emailTo)
        {
            // Add these to the "To" address
            objEmail.To.Add(address);
        }

        // Check for CC addresses

        if (cc != "")
        {
            string[] emailCC = cc.Split(',');
            foreach (string addressCC in emailCC)
            {
                objEmail.CC.Add(addressCC);
            }
        }

        // Check for Bcc addresses

        if (Bcc != "")
        {
            string[] emailBCC = Bcc.Split(',');
            foreach (string addressBCC in emailBCC)
            {
                objEmail.Bcc.Add(addressBCC);
            }
        }

        // Set the subject.
        objEmail.Subject = subject;

        // Set the email body
        objEmail.Body = emailBody;

        // Set up the SMTP client

        SmtpClient server = new SmtpClient();


        switch (client)
        {
            case "iis":
                server.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                break;
            case "network":
                server.DeliveryMethod = SmtpDeliveryMethod.Network;
                NetworkCredential credentials = new NetworkCredential("SmtpUserName", "SmtpPassword");
                server.Host = "SmtpHost";
                server.Port = 26;
                server.Credentials = credentials;
                break;
            case "directory":
                server.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                server.PickupDirectoryLocation = "c:\\mailpickup";
                break;
            default:
                throw new Exception("Invalid delivery method specified, cannot continue!");

        }

        if (html)
        {
            // As the email is HTML, we need to strip out all tags for the plaintext version of the email.
            string s = emailBody;

            s = Regex.Replace(s, "<.*?>", string.Empty);
            s = Regex.Replace(s, "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);

            AlternateView plainText = AlternateView.CreateAlternateViewFromString(s, null, MediaTypeNames.Text.Plain);
            objEmail.AlternateViews.Add(plainText);

            AlternateView rich = AlternateView.CreateAlternateViewFromString(emailBody, null, MediaTypeNames.Text.Html);
            objEmail.AlternateViews.Add(rich);
        }


        try
        {
            server.Send(objEmail);
            return true;
        }
        catch(Exception ex)
        {
            throw new Exception(ex.ToString());
        }
Run Code Online (Sandbox Code Playgroud)

正如我所说,页面在大约 60 秒后完全挂起,看不到任何错误消息。

提前致谢,

戴夫

添加: - 这就是我调用 sendMail() 的方式

webMail sendConfirmation = new webMail();

fileSystem fs = new fileSystem();
siteSettings setting = new siteSettings();
string mailBody = fs.file_get_contents("http://myurl.com/mymessage.html");

// Run any replaces.
mailBody = mailBody.Replace("{EMAIL_TITLE}", "Your account requires confirmation");
mailBody = mailBody.Replace("{U_FNAME}", u_forename);
mailBody = mailBody.Replace("{REG_URL_STRING}", setting.confirmUrl);


sendConfirmation.sendMail(u_emailAddress, "Your account requires confirmation", mailBody, setting.siteEmail);
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 5

您可以尝试检查错误:

SmtpClient smtp = new SmtpClient();
            smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
            smtp.Send(msgMail);

void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        if (e.Cancelled == true || e.Error != null)
        {
            throw new Exception(e.Cancelled ? "EMail sedning was canceled." : "Error: " + e.Error.ToString());
        }
Run Code Online (Sandbox Code Playgroud)