C#SmtpClient发送失败:提供了无效参数

时间:2018-02-24 00:47:10

标签: c#

我正在尝试使用Office365邮件服务器发送邮件,并且在没有解决方案的情况下不断遇到此问题/异常。对此进行了大量研究,找不到任何类似问题的帖子:

System.Net.Mail.SmtpException: Failure sending mail. 
---> System.Net.Sockets.SocketException: An invalid argument was supplied
at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at whatever.Main()

这是我的C#代码(我为了便于分析而对其进行了简化):

using System;
using System.Net;
using System.Net.Mail;

class whatever
{
    static int Main()
    {
        try
        {
            MailMessage mail = new MailMessage(
                "blah@blah.com",
                "blah@blah.com",
                "no subject",
                "no body");

            SmtpClient client = new SmtpClient("outlook.office365.com");

            client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("blah@blah.com", "mypass");
            client.EnableSsl = true;

            client.Send(mail);
            Console.WriteLine("mail Send");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        return 0;
    }
}

使用带有TLS的Python(端口587)的类似Sendmail方法可以工作但不能使用此C#代码,因此我的PC和Office365 SMTP服务器之间不应存在连接问题。

非常感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:-1)

根据Microsoft documentation,您的smtp地址似乎不正确。

请更改:

SmtpClient client = new SmtpClient("outlook.office365.com");

要:

SmtpClient client = new SmtpClient("smtp.office365.com");

更多信息here