对于我的应用程序,我有代码发送实时/ 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,所以我认为这也不是问题。
答案 0 :(得分: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;
答案 1 :(得分: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());
}