2011-02-14 193 views
0

我正嘗試使用Gmail在C#中發送電子郵件。每當用戶收到電子郵件時,我都希望「發件人」標題擁有另一個自己指定的電子郵件地址。任何人都可以告訴我我該怎麼做?通過Gmail帳戶發送電子郵件問題

MailMessage mailMsg = new MailMessage(); 
SmtpClient client = new SmtpClient(); 

client.Port = 587; 
client.Host = "smtp.gmail.com"; 
client.EnableSsl = true; 
client.Credentials = new System.Net.NetworkCredential(username, password); 
MailAddress mailAdd = new MailAddress("[email protected]"); 

mailMsg.Sender = new MailAddress(username); 
mailMsg.From = mailAdd; 
//mailMsg.Headers.Add("Sender",username); 
mailMsg.Bcc.Add(builder.ToString()); 

mailMsg.Subject = txtSubject.Text; 
mailMsg.Body = txtBody.Text; 
mailMsg.IsBodyHtml = chkHtmlBody.Checked; 
if (System.IO.File.Exists(txtAttechments.Text)) 
{ 
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text); 
mailMsg.Attachments.Add(attechment); 
} 

client.Send(mailMsg); 

在上面的代碼'用戶名'和'密碼'字段中包含另一個電子郵件地址和密碼。收到的電子郵件有'來自'標頭,值爲

+0

重複的http://stackoverflow.com/questions/3304699/how-to-set-from-address-to-any-email-other-gmail-in-sending-email-in-net- thro和http://stackoverflow.com/questions/3871577/change-sender-address-when-sending-mail-through-gmail-in-c。基本上,使用Gmail,無法完成(按設計) – 2011-02-14 12:02:00

回答

0

如果您的郵件提供的不是Gmail,也不使用IMAP服務,請嘗試此操作。

MailMessage mailMsg = new MailMessage(); 
SmtpClient client = new SmtpClient(); 

client.Port = 587; 
client.Host = "mail.youdomain.com"; //////EDITED 
client.EnableSsl = false; //////EDITED 
client.Credentials = new System.Net.NetworkCredential(username, password); 
MailAddress mailAdd = new MailAddress("[email protected]"); 

mailMsg.Sender = new MailAddress(username); 
mailMsg.From = mailAdd; 
//mailMsg.Headers.Add("Sender",username); 
mailMsg.Bcc.Add(builder.ToString()); 

mailMsg.Subject = txtSubject.Text; 
mailMsg.Body = txtBody.Text; 
mailMsg.IsBodyHtml = chkHtmlBody.Checked; 
if (System.IO.File.Exists(txtAttechments.Text)) 
{ 
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text); 
mailMsg.Attachments.Add(attechment); 
} 

client.Send(mailMsg); 
+0

他明確表示他使用的是Gmail,因此您的解決方案無法正常工作。他應該讀這個線程http://stackoverflow.com/questions/4677258/send-email-using-system-net-mail-through-through-gmail-c – 2011-02-14 17:20:31

相關問題