实时服务器上的 SMTP 类出错

发布于 2024-11-02 10:56:24 字数 8270 浏览 1 评论 0原文

我有一个带有运行 .NET 3.5 的 ASP.NET MVC 后端的网站。在这个网站上,有一个使用 gmail 作为邮件服务发送电子邮件的脚本。该脚本在我的开发计算机上本地运行并发送邮件,但一旦我将其上传到实时服务器,它就会失败。目前它给我的唯一错误消息是(因为我告诉它,您将在下面看到):

传输无法连接到服务器。

这是邮件程序脚本的代码:

using System.Net.Mail;
using System.Web.Mail;
using MailMessage = System.Web.Mail.MailMessage;

namespace MySite.Helpers
{
    public class GmailHelper
    {
        private readonly int _port = 465;
        private readonly string _accountName;
        private readonly string _password;

        public GmailHelper(string accountName, string password)
        {
            _accountName = accountName;
            _password = password;
        }
        public GmailHelper(string accountName, string password, int port)
        {
            _accountName = accountName;
            _password = password;
            _port = port;
        }
        public void Send(string from, string to, string subject, string body, bool isHtml)
        {
            Send(from, to, subject, body, isHtml, null);
        }

        public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
        {

            var mailMessage = new MailMessage

                                                          {
                                                              From = from,
                                                              To = to,
                                                              Subject = subject,
                                                              Body = body,
                                                              BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
                                                          };


            // Add attachments
            if (attachments != null)
            {
                foreach (var t in attachments)
                {
                    mailMessage.Attachments.Add(new Attachment(t));
                }
            }

            //  Authenticate
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
            // Username for gmail - [email protected] for email for Google Apps
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
            // Password for gmail account
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
            // Google says to use 465 or 587.  I don't get an answer on 587 and 465 works - YMMV
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
            // STARTTLS 
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

            // assign outgoing gmail server
            SmtpMail.SmtpServer = "smtp.gmail.com";
            SmtpMail.Send(mailMessage);
        }
    }
}

它的名称是这样的:

[HttpPost]
public ActionResult Employment(EmploymentModel model, FormCollection collection)
{
    if (!ModelState.IsValid)
        return View(model);

    var results = new EmploymentViewModel();
    try
    {

        results.Position = model.Position;
        results.FirstName = model.FirstName;
        results.LastName = model.LastName;
        results.ContactPhone = model.ContactPhone;
        results.OtherPhone = model.OtherPhone;
        results.Address = model.Address;
        results.Email = model.Email;
        results.HsDiploma = model.HsDiploma.ToString();
        results.CollegeYears = model.CollegeYears;
        results.Skills = model.Skills;
        results.Employment = model.Employment;
        results.DateSent = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

        var gmail = new GmailHelper("[email protected]", "[*removed*]");

        var fromAddress = new MailAddress("[email protected]", "MySite");
        var toAddress = new MailAddress("[email protected]", "MySite Employment");
        var subject = string.Format("Employment Application for {0} {1}", model.FirstName, model.LastName);

        gmail.Send(fromAddress.Address, toAddress.Address, subject, EmployMailBody(results), false);
    }
    catch (Exception ex)
    {
        results.Sent = false;
        results.Title = "Oops, our mail drone seems to have malfunctioned!";
        results.Message = string.Format("We appologize, {0} {1}, but our email system has encountered an error and your email was not sent.</p>",
                results.FirstName, results.LastName);
        results.Message += Environment.NewLine + "<p>Please try your request later, or fax your résumé to our Corporate office.";
        results.Message += Environment.NewLine + JQueryHelpers.GenerateErrorField(ex.Message);

        return View("EmploymentSubmit", results);
    }
    results.Sent = true;
    results.Title = "Thank you for your submission!";
    results.Message = string.Format("Thank you for your interest in joining our team, {0} {1}!</p>", results.FirstName, results.LastName);
    results.Message += Environment.NewLine + "<p>We have successfully recieved your information and will contact you shortly at the number your have provided.";

    return View("EmploymentSubmit", results);
}

我 99% 确信它在网站上发布之前就可以正常工作,但我可能会弄错,因为自从我必须更新网站以来,已经有一个月左右的时间了。

我是否可以采取一些额外的步骤来“更好地”调试这个问题以追踪根本问题,或者我是否意外地在某个地方搞砸了我的代码?

谢谢!

EDIT1

所以我更新了类以严格使用 System.Net.Mail 。我成功地从我的开发机器发送了一条消息。然而,当我将该网站上传到我的服务器时,我收到了一条新的错误消息:

请求类型为“System.Net.Mail.SmtpPermission、System、Version=2.0.0.0、Culture=neutral、PublicKeyToken= 的权限” b77a5c561934e089' 失败。

该网站由 godaddy.com 托管,有些人在搜索后似乎 godaddy 只允许通过他们的 smtp 服务器进行中继。看来我必须更换托管提供商才能使其正常工作。

谢谢!

EDIT2

我从 godaddy 转移到 gmail 的原因最初是当我安装此脚本时,电子邮件将需要 15 到 45 分钟才能到达目的地框。这可能是我之前使用的已弃用的代码,但无论哪种方式,它现在都在几秒钟内被调度并到达,正如它应该的那样。这是我的 GoDaddy 帮助程序类,以防它对某人有帮助:

public class GoDaddyHelperNet
{
    private readonly int _port = 25;
    private readonly MailAddress _accountName;
    private readonly string _password;
    private readonly string _host = "relay-hosting.secureserver.net";

    public GoDaddyHelperNet(MailAddress accountName, string password)
    {
        _accountName = accountName;
        _password = password;
    }
    public GoDaddyHelperNet(MailAddress accountName, string password, int port)
    {
        _accountName = accountName;
        _password = password;
        _port = port;
    }
    public GoDaddyHelperNet(MailAddress accountName, string password, int port, string host)
    {
        _accountName = accountName;
        _password = password;
        _port = port;
        _host = host;
    }
    public void Send(MailAddress to, string subject, string body, bool isHtml)
    {
        Send(_accountName, to, subject, body, isHtml);
    }

    public void Send(MailAddress from, MailAddress to, string subject, string body, bool isHtml)
    {
        var smtp = new SmtpClient
                       {
                           Host = _host,
                           Port = _port,
                           EnableSsl = false,
                           DeliveryMethod = SmtpDeliveryMethod.Network,
                           UseDefaultCredentials = false,
                           Credentials = new NetworkCredential(from.Address, _password),
                           Timeout = 15000
                       };

        using (var message = new System.Net.Mail.MailMessage(from.Address, to.Address)
                     {
                         Subject = subject,
                         Body = body,
                     })

            smtp.Send(message);
    }
}

I have a website with an ASP.NET MVC backend running .NET 3.5. On this website, there is a script that sends emails using gmail as the mail service. The script runs and sends mail fine locally on my dev machine, but as soon as I upload it to the live server it fails. The only error message it is giving me at the moment is (since I told it to as you will see further down):

The transport failed to connect to the server.

Here is the code for the mailer script:

using System.Net.Mail;
using System.Web.Mail;
using MailMessage = System.Web.Mail.MailMessage;

namespace MySite.Helpers
{
    public class GmailHelper
    {
        private readonly int _port = 465;
        private readonly string _accountName;
        private readonly string _password;

        public GmailHelper(string accountName, string password)
        {
            _accountName = accountName;
            _password = password;
        }
        public GmailHelper(string accountName, string password, int port)
        {
            _accountName = accountName;
            _password = password;
            _port = port;
        }
        public void Send(string from, string to, string subject, string body, bool isHtml)
        {
            Send(from, to, subject, body, isHtml, null);
        }

        public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
        {

            var mailMessage = new MailMessage

                                                          {
                                                              From = from,
                                                              To = to,
                                                              Subject = subject,
                                                              Body = body,
                                                              BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
                                                          };


            // Add attachments
            if (attachments != null)
            {
                foreach (var t in attachments)
                {
                    mailMessage.Attachments.Add(new Attachment(t));
                }
            }

            //  Authenticate
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
            // Username for gmail - [email protected] for email for Google Apps
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
            // Password for gmail account
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
            // Google says to use 465 or 587.  I don't get an answer on 587 and 465 works - YMMV
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString());
            // STARTTLS 
            mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

            // assign outgoing gmail server
            SmtpMail.SmtpServer = "smtp.gmail.com";
            SmtpMail.Send(mailMessage);
        }
    }
}

And here is how it is called:

[HttpPost]
public ActionResult Employment(EmploymentModel model, FormCollection collection)
{
    if (!ModelState.IsValid)
        return View(model);

    var results = new EmploymentViewModel();
    try
    {

        results.Position = model.Position;
        results.FirstName = model.FirstName;
        results.LastName = model.LastName;
        results.ContactPhone = model.ContactPhone;
        results.OtherPhone = model.OtherPhone;
        results.Address = model.Address;
        results.Email = model.Email;
        results.HsDiploma = model.HsDiploma.ToString();
        results.CollegeYears = model.CollegeYears;
        results.Skills = model.Skills;
        results.Employment = model.Employment;
        results.DateSent = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");

        var gmail = new GmailHelper("[email protected]", "[*removed*]");

        var fromAddress = new MailAddress("[email protected]", "MySite");
        var toAddress = new MailAddress("[email protected]", "MySite Employment");
        var subject = string.Format("Employment Application for {0} {1}", model.FirstName, model.LastName);

        gmail.Send(fromAddress.Address, toAddress.Address, subject, EmployMailBody(results), false);
    }
    catch (Exception ex)
    {
        results.Sent = false;
        results.Title = "Oops, our mail drone seems to have malfunctioned!";
        results.Message = string.Format("We appologize, {0} {1}, but our email system has encountered an error and your email was not sent.</p>",
                results.FirstName, results.LastName);
        results.Message += Environment.NewLine + "<p>Please try your request later, or fax your résumé to our Corporate office.";
        results.Message += Environment.NewLine + JQueryHelpers.GenerateErrorField(ex.Message);

        return View("EmploymentSubmit", results);
    }
    results.Sent = true;
    results.Title = "Thank you for your submission!";
    results.Message = string.Format("Thank you for your interest in joining our team, {0} {1}!</p>", results.FirstName, results.LastName);
    results.Message += Environment.NewLine + "<p>We have successfully recieved your information and will contact you shortly at the number your have provided.";

    return View("EmploymentSubmit", results);
}

I am 99% positive that it was functional before when it was up on the site, but I could be mistaken as it has been a month or so since I have had to update the site.

Are there some additional steps I can take to debug this "better" to track down the underlying issue, or did I botch up my code somewhere accidentally?

Thanks!

EDIT1

So I updated the class to use strictly System.Net.Mail. I successfully sent a message from my dev machine. When I uploaded the site to my server, however, I got a new error message:

Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

This site is hosted through godaddy.com, and some after searching around it seems godaddy only allows relaying through their smtp server. It looks like I'll have to change hosting providers to get this working properly.

Thanks!

EDIT2

The reason I moved to gmail from godaddy is originally when I had this script up the email would take anywhere from 15 to 45 minutes to arrive at the destination box. This could have been the deprecated code I was using before, but either way it is now being dispatched and arriving within seconds, as it should be. Here is my GoDaddy helper class, in case it will help someone:

public class GoDaddyHelperNet
{
    private readonly int _port = 25;
    private readonly MailAddress _accountName;
    private readonly string _password;
    private readonly string _host = "relay-hosting.secureserver.net";

    public GoDaddyHelperNet(MailAddress accountName, string password)
    {
        _accountName = accountName;
        _password = password;
    }
    public GoDaddyHelperNet(MailAddress accountName, string password, int port)
    {
        _accountName = accountName;
        _password = password;
        _port = port;
    }
    public GoDaddyHelperNet(MailAddress accountName, string password, int port, string host)
    {
        _accountName = accountName;
        _password = password;
        _port = port;
        _host = host;
    }
    public void Send(MailAddress to, string subject, string body, bool isHtml)
    {
        Send(_accountName, to, subject, body, isHtml);
    }

    public void Send(MailAddress from, MailAddress to, string subject, string body, bool isHtml)
    {
        var smtp = new SmtpClient
                       {
                           Host = _host,
                           Port = _port,
                           EnableSsl = false,
                           DeliveryMethod = SmtpDeliveryMethod.Network,
                           UseDefaultCredentials = false,
                           Credentials = new NetworkCredential(from.Address, _password),
                           Timeout = 15000
                       };

        using (var message = new System.Net.Mail.MailMessage(from.Address, to.Address)
                     {
                         Subject = subject,
                         Body = body,
                     })

            smtp.Send(message);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷情 2024-11-09 10:56:24

可能有防火墙规则或其他网络设备阻止了您。验证您是否可以从 Web 服务器远程登录到 Gmail 服务器并且可以发送电子邮件。

http://www.wikihow.com/Send-Email-Using-Telnet

如果不能,您可能需要与您的网络管理员联系。我大约一半的客户网络服务器上都有这样的电子邮件问题。

there is probably a firewall rule or other network device blocking you. verify that you can telnet to the gmail server from your web server and can send an email.

http://www.wikihow.com/Send-Email-Using-Telnet

if you can't you probably have to talk to your network admin. i have email problems like this on about half of my clients web servers.

夜灵血窟げ 2024-11-09 10:56:24

Gmail 对 SMTP 中继有很多限制。 IIRC 每天的收件人总数不超过 100 人。每条消息的收件人也有限制。消息/附件大小的限制。如果您超出限制或 Gmail 认为您看起来像垃圾邮件艺术家,他们的 SMTP 服务器可能会拒绝连接一天左右。

Gmail has got lots of restrictions on SMTP relay. No more than 100 total recipients per day, IIRC. Limits on recipients per message as well. Limits on message/attachment size. If you exceed the limits or Gmail has decided that you look like a spam artiste, their SMTP server may well refuse the connection for a day or so.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文