我的C#代码无法发送邮件,但outlook 2k7可以

时间:2013-08-06 04:51:56

标签: c# sendmail smtpclient

我写了C#代码来发送邮件(我的公司邮件)。我尝试使用gmail并且它正常工作,但我的公司邮件却没有。

我确定smtp服务器正在运行并且端口465已打开,因为我可以通过outlook 2k7使用相同的帐户发送邮件,telnet smtp.domain 465 ok。

当我运行代码时,它会抛出异常“System.Net.Mail.SmtpException:操作超时。”

这是我的c#代码:

        var fromAddress = new MailAddress("ID@domain", "Display Name");
        var toAddress = new MailAddress("ID@domain", "Display Name");
        const string subject = "Test mail";
        const string body = "Test mail";

        var smtp = new SmtpClient
        {
            Host = "smtp.domain",
            Port = 465,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential("ID", "pass"),
            Timeout=15000                
        };

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body,

        })
        {
            try
            {
                smtp.Send(message);
                MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

任何人都知道或有相同的问题,请帮助我。非常感谢!

2 个答案:

答案 0 :(得分:0)

尝试在SmtpClient实例中更改设置EnableSsl = false。

答案 1 :(得分:0)

您可以更改此代码并重复使用此代码:

        public static void sendEmail(string address, string subject, string message)
        {
            string email = "yourEmail";
            string password = "yourPass";

            var loginInfo = new NetworkCredential(email, password);
            var msg = new MailMessage();
            var smtpClient = new SmtpClient("smtp.gmail.com", portNumber);

            msg.From = new MailAddress(email);
            msg.To.Add(new MailAddress(address));
            msg.Subject = subject;
            msg.Body = message;
            msg.IsBodyHtml = true;

            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = loginInfo;
            smtpClient.Send(msg);
        }