我正在尝试学习如何使用c#visual studio forms应用程序发送简单的电子邮件。 (它也可以是我所关心的所有控制台应用程序)。这是我的代码(我没有看到代码有什么问题,它应该正常工作吗?):
using System.Net.Mail;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("(here is my email)");
mail.To.Add("(here is my email)");
mail.Subject = "toja";
mail.Body = "ja";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("(here is my email)", "(here is my password)");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
答案 0 :(得分:0)
我使用以下内容从C#Forms应用程序发送电子邮件,它可以正常工作。 也许你应该尝试添加smtp.UseDefaultCredentials = false属性并设置Credentials属性?
// Create our new mail message
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("toAddress");
mailMessage.From = new MailAddress("fromAddress");
mailMessage.Subject = "subject";
mailMessage.Body = "body";
// Set the IsBodyHTML option if it is HTML email
mailMessage.IsBodyHtml = true;
// Enter SMTP client information
SmtpClient smtpClient = new SmtpClient("mail.server.address");
NetworkCredential basicCredential = new NetworkCredential("username", "password");
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Send(mailMessage);
如果使用Gmail,您可以在https://support.google.com/a/answer/176600?hl=en找到SMTP服务器信息。看起来地址为smtp.gmail.com
,SSL的端口为465
,TLS的端口为587
。我建议您首先尝试使用默认端口25以确保您的电子邮件通过,然后根据需要调整到其他端口。