通过C#发送Gmail

时间:2010-06-28 02:02:04

标签: c#-3.0 gmail

  

可能重复:
  Sending Email in .NET Through Gmail

通过C#发送邮件有很多问题。我已经在多个应用上永远尝试过,它永远不会有效......

有人可以发布一些示例代码,清楚标明发件人和收件人去哪里,并提供有关smtp服务器数据的帮助!!

3 个答案:

答案 0 :(得分:2)

这样的事情:

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("sender@gmail.com", "recipient@example.com", "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);

答案 1 :(得分:2)

我之前写的一些代码,用于通过网络表单发送电子邮件:

    //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
    }

答案 2 :(得分:0)

我让这个类在我的开发环境中通过我的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);

    }
}