[英]Sending mail via C#
我正在尝试使用gmail stmp服务器通过C#向自己发送电子邮件,但我收到了来自gmail团队的电子邮件,内容是: “ Google刚刚阻止了不安全的应用访问您的Google帐户。” 。 现在,我更改了设置,以允许安全性较低的应用登录google,但无法向自己发送电子邮件。以下是我的代码。
private static string sendMail(System.Net.Mail.MailMessage mm)
{
try
{
string smtpHost = "smtp.gmail.com";
string userName = "myemail@gmail.com";//write your email address
string password = "xxxxxx";//write password
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return "Send Sucessfully";
}
private void f()
{
i = i + 1;
string sysName = string.Empty;
string sysUser = string.Empty;
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("myemail@gmail.com");
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("myemail@gmail.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
sysName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
sysUser = System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString();
mm.Subject = sysName + " " + sysUser;
string filename = string.Empty;
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
MessageBox.Show(sendMail(mm).ToString());
//sendMail(mm);
}
private void Form1_Load(object sender, EventArgs e)
{
f();
}
我也尝试过使用Yahoo帐户进行同样的操作。然后我也没有收到任何电子邮件。 我已将端口更改为465,将smtphost更改为“ mail.yahoo.com”,并将电子邮件地址更改为mymail@yahoo.com
protected void SendMail()
{
// Gmail Address from where you send the mail
var fromAddress = "Gmail@gmail.com";
// any address where the email will be sending
var toAddress = YourEmail.Text.ToString();
//Password of your gmail address
const string fromPassword = "Password";
// Passing the values and make a email formate to display
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
您已使用此代码。 它正在运行代码。
转到Google帐户设置,并允许安全性较低的应用程序。 https://myaccount.google.com/u/1/security?utm_source=OGB#signin在底部的“允许安全程度较低的应用程序”滑块是您需要使用的滑块。
默认的Google SMTP设置在此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.