gpt4 book ai didi

c# - 在 asp.net 中发送邮件-也使用 web 配置

转载 作者:太空狗 更新时间:2023-10-30 00:19:24 25 4
gpt4 key购买 nike

我正在尝试创建一个联系我们的页面,用户在其中单击提交并向我发送电子邮件,我查看了一些示例,但他们似乎将他们的电子邮件凭据硬编码到代码中,我发现security m 您可以将用户名和密码存储在 webconfig 文件中,下面是我的 web 配置代码和我的默认 aspx.cs 代码,任何人都可以帮我解决这个问题,这是我得到的错误

The remote name could not be resolved: 'smtp.gmail.com,587' Line 45: mailClient.Send(message);

这是我的应用程序设置和代码:

        <appSettings>
<add key="PFUserName" value="myemail@gmail.com"/>
<add key="PFPassWord" value="mypassword"/>
<add key="MailServerName" value="smtp.gmail.com,587"/>
</appSettings>


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Web.Configuration;
using System.Net;

namespace WebApplication2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
SendMail(txtEmail.Text, txtComments.Text);
}

private void SendMail(string from, string body)
{
string Username = WebConfigurationManager.AppSettings["PFUserName"].ToString();
string Password = WebConfigurationManager.AppSettings["PFPassWord"].ToString();
string MailServer = WebConfigurationManager.AppSettings["MailServerName"].ToString();
NetworkCredential cred = new NetworkCredential(Username, Password);
string mailServerName = ("smtp.gmail.com,587");



MailMessage message = new MailMessage(from, Username, "feedback", body);
SmtpClient mailClient = new SmtpClient("smtp.gmail.com,587");
mailClient.EnableSsl = true;

mailClient.Host = mailServerName;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = cred;
mailClient.Send(message);
message.Dispose();

}
}

最佳答案

您需要像这样在 web.config 的 mailSettings 配置中设置 SMTP 设置

  <system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="my@mail.com">
<network host="smtp.gmail.com" port="587" userName="myemail@gmail.com" password="mypassword" />
</smtp>
</mailSettings>
</system.net>

您的服务器名称是 smtp.gmail.com(从那里删除 587)。 587 是 smtp 使用的端口。所以把这个值放在主机属性中。

C#代码:

SmtpClient smtpClient = new SmtpClient();
MailMessage mailMessage = new MailMessage();

mailMessage.To.Add(new MailAddress("sender@mail.com"));
mailMessage.Subject = "mailSubject";
mailMessage.Body = "mailBody";

smtpClient.Send(mailMessage);

关于c# - 在 asp.net 中发送邮件-也使用 web 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21192266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com