change sender address when sending mail through gmail in c#

倾然丶 夕夏残阳落幕 提交于 2019-11-26 04:51:22

问题


I have used the following code to send mail from my web application using a gmail account. My question is, can i change the sender address to another address other than original sender(gmail) address? My code is as follows:

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential cred = new System.Net.NetworkCredential(\"sample@gmail.com\", \"*******\");

Whatever i do is useless as i always receive mail from sample@gmail.com. Is it possible to change it?

I have changed to mail.From = new System.Net.Mail.MailAddress(\"sample@yahoo.com\"); but i received the mail with the from address sample@gmail.com and not from the new \"From\" address. I think gmail smtp overwrites the from address with the original credential.


回答1:


Gmail doesn't allow you to change the FROM to something different than your gmail account.

It doesn't matter what you use, they over-write it, before they relay it on. This prevent spamming/spoofing.




回答2:


This is the solution:

  1. use the codes above to set mail.From = new MailAddress(address, display name)
  2. in Gmail, go to Mail Settings >> Accounts and Import.
  3. Add the email account you will use as sender in "Send Mail As". (tick as Alias)

This works for me




回答3:


Yes just use the From property of the MailMessage

eg.

mail.From = "newemail@email.com";

EDIT: Also, see this post for more detailed info on how to emails via gmail in C#

Sending email in .NET through Gmail

EDIT: Although this works for mail in general, it appears this won't work for gmail as google overwrite it before its sent (see @Dave wanta's answer)




回答4:


If you have a limited number of senders you can do as @philip suggested. For instance you may have customerservice@example.com, simon@example.com and philip@example.com or even alias@example.com. As long as they are approved senders on the actual gmail.com website you can send from them.

Gmail.com : Sending mail from a different address

If you are expecting to send from an arbitrary user (such as a customer service form on a website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));

If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).




回答5:


Check #56 and #58. They might be relevant to what you want to do https://code.google.com/p/google-apps-script-issues/issues/detail?id=172



来源:https://stackoverflow.com/questions/3871577/change-sender-address-when-sending-mail-through-gmail-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!