[英]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.