C#Windows窗体应用程序 - 使用gmail smtp发送电子邮件

时间:2013-03-21 02:36:58

标签: c# winforms smtp

我一直在尝试创建一个通过smtp.gmail.com发送电子邮件的小程序,但它总是提示我“操作已经超时”。 我知道网上有很多可用的解决方案,但都没有。

try
{
    MailMessage message = new MailMessage();
    SmtpClient smtp = new SmtpClient();

    message.From = new MailAddress("from@gmail.com");
    message.To.Add(new MailAddress("to@gmail.com"));
    message.Subject = "Test";
    message.Body = "Content";

    smtp.Port = 465;
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("from@gmail.com", "pwd");
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Send(message);
}
catch (Exception ex)
{
    MessageBox.Show("err: " + ex.Message);
}

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:11)

将端口更改为587:

try
{
    MailMessage message = new MailMessage();
    SmtpClient smtp = new SmtpClient();

    message.From = new MailAddress("from@gmail.com");
    message.To.Add(new MailAddress("to@gmail.com"));
    message.Subject = "Test";
    message.Body = "Content";

    smtp.Port = 587;
    smtp.Host = "smtp.gmail.com";
    smtp.EnableSsl = true;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential("from@gmail.com", "pwd");
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Send(message);
}
catch (Exception ex)
{
    MessageBox.Show("err: " + ex.Message);
}

答案 1 :(得分:1)

如何在c#windows中发送存储在d盘中的pdf文件的电子邮件     申请......答案是......

MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress(txtFrom.Text.ToString());
            mail.To.Add(txtmailTo.Text.ToString());
            mail.Subject = "Mail Pdf";
            var filename = @"D:/your file path/.pdf";
            mail.Attachments.Add(new Attachment(filename));
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new 
            System.Net.NetworkCredential(txtFrom.Text, txtPassword.Text);
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);