我们可以使用asp.net和c#从本地主机发送邮件吗?
本文关键字:主机 asp 可以使 net 我们 | 更新日期: 2023-09-27 18:04:14
我使用的是using System.Net.Mail;
和下面的代码发送邮件
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress("fromAddress");
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// Set the SMTP server to be used to send the message
client.Host = "YourMailServer";
// Send the e-mail message
client.Send(message);
主机我提供client.Host = "localhost";
对于这个,它的下落带有错误
无法连接,因为目标机器处于活动状态拒绝some_ip_address_here
和当我使用client.Host = "smtp.gmail.com";
我得到以下错误
连接尝试失败,因为被连接的一方没有一段时间后适当回应,或建立联系失败,因为连接的主机未能响应
我无法通过localhost发送邮件。请帮助我,我是新的c#请纠正我的代码在哪里我错了…?
下面是一些通过gmail发送邮件的代码(代码来自某个地方的stackoverflow)。它类似于这里的代码:Gmail:如何以编程方式发送电子邮件):
using (var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("yourmail@gmail.com", "yourpassword"),
EnableSsl = true
})
{
client.Send("frommail@gmail.com", "tomail@gmail.com", "subject", message);
}
从client.Host = "localhost"
发送邮件需要设置本地SMTP服务器。
通过谷歌发送邮件(或通过任何其他SMTP服务器,包括你自己的本地SMTP),你必须设置用户名,密码,ssl设置-所有的SMTP服务器所选择的要求,你需要阅读他们的帮助。
例如,谷歌说你需要SSL,端口465或587,服务器smtp.gmail.com
和你的用户名和密码。
您可以在.config文件中分配所有这些值。
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="yourname@gmail.com" password="password" />
</smtp>
</mailSettings>
</system.net>
或者在每次使用前设置为SmtpClient:
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSSL = true;
client.Credentials = new NetworkCredential("yourname@gmail.com", "password");
将此代码放置在web中的<configuration> </configuration>
中。配置文件
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="youremail@gmail.com" password="yourpassword" />
</smtp>
</mailSettings>
</system.net>
然后后台代码
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("email@gmail.com");
message.To.Add(new MailAddress(TextBoxEadd.Text));
message.CC.Add(new MailAddress("email@gmail.com"));
message.Subject = "New User Registration ! ";
message.Body = "HELLO";
sr.Close();
SmtpClient client = new SmtpClient();
client.Send(message);
希望这段代码对你有所帮助!:)
使用这一行,不要使用端口和主机名
LocalClient。
我只是想补充一下,Gmail现在需要应用程序密码才能从其他应用程序使用它。点击这个链接。我得费一番周折才找到。在我创建了一个应用程序密码之后,然后我更改了NetworkCredentials以使用它来发送电子邮件。