为什么SmtpMail不发送,除非在web.config中设置了from/host

本文关键字:设置 config from host web SmtpMail 为什么 | 更新日期: 2023-09-27 17:57:26

我正在尝试使用SmtpMail发送电子邮件。在我的本地服务器上,即使代码中设置了主机/服务器、密码和发件人信息,我也可以这样做。在我的托管服务(1和1)上,只有当我在web.config文件中设置了这些内容时,它才会发送!有人知道是什么原因造成的吗(1和1不知道)。

在本地工作,但不在托管服务上

<%@ Page language="c#" %>
<%@ Import namespace="System.Net.Mail" %>
<%
    MailMessage mail = new MailMessage();
    //Set my from address
    mail.From = new MailAddress( "myemail@myemail.com");
    //Who I'm sending to
    mail.To.Add( new MailAddress("you@you.com") );
    mail.Subject = "A test";
    mail.Body = "Test message";
    //Set the mail server (default should be smtp.1and1.com)
    SmtpClient smtp = new SmtpClient( "smtp.1and1.com" );
    //Enter your full e-mail address and password
    smtp.Credentials = new NetworkCredential("myemail@myemail.com", "mypassword");
    //Send the message
    smtp.Send(mail);
%>

这就是我让它在主机上工作的方式(两个文件,测试页和web.config)

<%@ Page language="c#" %>
<%@ Import namespace="System.Net.Mail" %>
<%
    MailMessage mail = new MailMessage();
    //Set my from address
    mail.From = new MailAddress( "myemail@myemail.com");
    //Who I'm sending to
    mail.To.Add( new MailAddress("you@you.com") );
    mail.Subject = "A test";
    mail.Body = "Test message";
    //Create with no server or credentials (grabs from web.config)
    SmtpClient smtp = new SmtpClient();
    //Send the message
    smtp.Send(mail);
%>

(和web.config)

    <configuration>
    <system.net>
        <mailSettings>
            <smtp from="myemail@myemail.com">
                <network host="smtp.1and1.com" port="25" userName="myemail@myemail.com" password="mypassword"/>
            </smtp>
        </mailSettings>
    </system.net>
</configuration>

为什么SmtpMail不发送,除非在web.config中设置了from/host

我看到您在使用本地代码时没有设置SMTP端口,而是在web.config中进行了设置。您是否尝试过手动添加SMTP端口,如下所示:

smtp.Port = 25;

此外,您是否尝试手动设置EnableSsSL属性?