0

对于我的应用程序,我有代码可以为 live/hotmail 发送电子邮件,但不是为 gmail 发送电子邮件,这不起作用我试图为它建立一个检查,以查看用于发送电子邮件的帐户,但它不起作用,当我尝试发送 Gmail 电子邮件时。这是我用于检查的代码:

MailMessage msg = new MailMessage();
            msg.To.Add(txtAan.Text);
            msg.From = new MailAddress(txtGebruikersnaam.Text);
            msg.Subject = txtOnderwerp.Text;
            msg.Body = txtBericht.Text;

            string smtpcheck = txtGebruikersnaam.Text;
            smtpcheck.Substring(Math.Max(0, smtpcheck.Length - 10));

            SmtpClient smtp = new SmtpClient();
            if (smtpcheck.ToLower() == "@gmail.com")
            {
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 25;
            }
            else if(smtpcheck.ToLower() != "@gmail.com")
            {
                smtp.Host = "smtp.live.com";
                smtp.Port = 587;
            }
            smtp.EnableSsl = true;
            smtp.Credentials = new NetworkCredential(txtGebruikersnaam.Text, txtWachtwoord.Text);
            smtp.Send(msg);

当我尝试使用 Gmail 发送电子邮件时,此代码给我一个错误,有人可以帮我解决这个问题吗?是的,我也尝试了端口:465 和 587 用于 gmail,所以我认为这也不是问题。

4

2 回答 2

4

此行不会更改 smtpcheck 的值

  smtpcheck.Substring(Math.Max(0, smtpcheck.Length - 10));

你需要写

  smtpcheck = smtpcheck.Substring(Math.Max(0, smtpcheck.Length - 10));

结果,您的 if 条件失败,并且您始终使用 live.com 发送邮件

编辑:对于 gmail,此代码已确认有效

 SmtpClient sc = new SmtpClient("smtp.gmail.com");
 NetworkCredential nc = new NetworkCredential("username", "password");
 sc.UseDefaultCredentials = false;
 sc.Credentials = nc;
 sc.EnableSsl = true;
 sc.Port = 587;
于 2012-12-10T18:16:16.540 回答
0
try
{
     MailMessage mail = new MailMessage();
     SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

     mail.From = new MailAddress("your_email_address@gmail.com");
     mail.To.Add("to_address");
     mail.Subject = "Test Mail";
     mail.Body = "This is for testing SMTP mail from GMAIL";

     SmtpServer.Port = 587;
     SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
     SmtpServer.EnableSsl = true;

     SmtpServer.Send(mail);
     MessageBox.Show("mail Send");
}
catch (Exception ex)
{
     MessageBox.Show(ex.ToString());
}
于 2012-12-10T18:17:40.230 回答