我有過C#發送郵件這麼多的問題。我已經永遠在多個應用程序嘗試,它永遠不會工作....
有人可能會發表一些示例代碼,清楚標記發件人和收件人去哪裏,並提供幫助與SMTP服務器數據或任何!
我有過C#發送郵件這麼多的問題。我已經永遠在多個應用程序嘗試,它永遠不會工作....
有人可能會發表一些示例代碼,清楚標記發件人和收件人去哪裏,並提供幫助與SMTP服務器數據或任何!
事情是這樣的:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("[email protected]", "[email protected]", "subject", "body");
System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 465);
emailClient.Credentials = new System.Net.NetworkCredential("yourgmailusername", "yourpassword");
emailClient.Send(message);
一些代碼,我寫了前一段時間通過一個Web窗體發送電子郵件:
//using System.Net.Mail;
MailMessage msg = new MailMessage();
msg.To.Add(RECIPIENT_ADDRESS); //note that you can add arbitrarily many recipient addresses
msg.From = new MailAddress(SENDER_ADDRESS, RECIPIENT_NAME, System.Text.Encoding.UTF8);
msg.Subject = SUBJECT
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = //SOME String
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(ADDRESS, PASSWORD);
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (SmtpException ex)
{
throw; //or handle here
}
我做了這個類通過我的Gmail帳戶發送時,在我的開發環境,並在生產中使用我的Web.Config中的SMTP。基本上與具有一定展開舒適性的貴族相同。
有一個標誌 「mailConfigTest」
/// <summary>
/// Send Mail to using gmail in test, SMTP in production
/// </summary>
public class MailGen
{
bool _isTest = false;
public MailGen()
{
_isTest = (WebConfigurationManager.AppSettings["mailConfigTest"] == "true");
}
public void SendMessage(string toAddy, string fromAddy, string subject, string body)
{
string gmailUser = WebConfigurationManager.AppSettings["gmailUser"];
string gmailPass = WebConfigurationManager.AppSettings["gmailPass"];
string gmailAddy = WebConfigurationManager.AppSettings["gmailAddy"];
NetworkCredential loginInfo = new NetworkCredential(gmailUser, gmailPass);
MailMessage msg = new MailMessage();
SmtpClient client = null;
if (_isTest) fromAddy = gmailAddy;
msg.From = new MailAddress(fromAddy);
msg.To.Add(new MailAddress(toAddy));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
if (_isTest)
{
client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
}
else
{
client = new SmtpClient(WebConfigurationManager.AppSettings["smtpServer"]);
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
}
參見[發送在.NET電子郵件通過Gmail](http://stackoverflow.com/questions/32260/sending-email-in-net-through -gmail)。如果你解釋「它永遠不會工作」 – 2010-06-28 02:06:23