通过SMTP发送电子邮件
本文关键字:电子邮件 SMTP 通过 | 更新日期: 2023-09-27 18:13:35
我在我的网站上有联系页面,我希望用户输入他们的姓名和电子邮件id(没有密码),并发送电子邮件按钮点击。
我做了谷歌和我得到的所有解决方案都需要用户密码,
public static void SendMessage(string subject, string messageBody, string toAddress, string ccAddress, string fromAddress)
{
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;
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtpHost";
smtp.Port =portno;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("fromEmail", "fromPassword");
smtp.Timeout = 20000;
}
// Send the e-mail message
smtp.Send(message);
}
但是我不想强迫用户输入密码。是否有其他使用SMTP的解决方案?
我得到的错误是A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
在我的实用程序类中有这个函数,它的工作效果非常好。
public static bool SendMail(string Email, string MailSubject, string MailBody)
{
bool isSent = false, isMailVIASSL = Convert.ToBoolean(ConfigurationManager.AppSettings["MailServerUseSsl"]);
string mailHost = ConfigurationManager.AppSettings["MailServerAddress"].ToString(),
senderAddress = ConfigurationManager.AppSettings["MailServerSenderUserName"].ToString(),
senderPassword = ConfigurationManager.AppSettings["MailServerSenderPassword"].ToString();
int serverPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]);
MailMessage msgEmail = new MailMessage(new MailAddress(senderAddress), new MailAddress(Email));
using (msgEmail)
{
msgEmail.IsBodyHtml = true;
msgEmail.BodyEncoding = System.Text.Encoding.UTF8;
msgEmail.Subject = MailSubject;
msgEmail.Body = MailBody;
using (SmtpClient smtp = new SmtpClient(mailHost))
{
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = isMailVIASSL;
smtp.Credentials = new NetworkCredential(senderAddress, senderPassword);
smtp.Port = serverPort;
try
{
smtp.Send(msgEmail);
isSent = true;
}
catch (Exception ex)
{
throw ex;
}
}
}
return isSent;
}
<!-- Mail Server Settings -->
<add key="MailServerAddress" value="smtp.gmail.com" />
<add key="MailServerPort" value="25" />
<add key="MailServerSenderUserName" value="username@gmail.com" />
<add key="MailServerSenderPassword" value="password" />
<add key="MailServerUseSsl" value="True" />