Search code examples
c#gmailsmtpclient

How to use any email address in the FROM field while sending email through Gmail SMTP?


I'm trying to send an email using gmail SMTP in C# using the code bellow

MailMessage message = new MailMessage();
message.To.Add("my email");
message.Subject = "subject";
message.From = new MailAddress("any email");
message.Body = "body";

message.Attachments.Add(new System.Net.Mail.Attachment(path));
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("my user", "my pass");

smtp.Send(message);

When I receive the email, the FROM field is filled with my user. I'm using UseDefaultCredentials as false. When I look to the result, the FROM field is filled with my user. Shouldn't the FROM field be filled with any email? How can I send an email using any email as sender?


Solution

  • Having run your code snippet I get:

    Return-Path: <my user>
    Received: from Psi ([80.92.234.64])
            by mx.google.com with ESMTPS id f1sm20531634wiy.2.2012.10.08.10.07.49
            (version=TLSv1/SSLv3 cipher=OTHER);
            Mon, 08 Oct 2012 10:07:49 -0700 (PDT)
    Message-ID: <[email protected]>
    Sender: Roman R. <my user>
    MIME-Version: 1.0
    From: any email
    To: my email
    Date: Mon, 08 Oct 2012 10:07:49 -0700 (PDT)
    Subject: Subject
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: quoted-printable
    
    Body
    

    Sender is the email address used to authenticate with Google Mail. From is the "from" provided in code. The receiving application might be confusing the two, and the rest looks just as expected. Some mail clients present the From+Sender (when they are different) as "sent by Sender on behalf of From".

    You might be concerned with the fact that Google Mail still reveal the account from which the email is sent, through Sender field, but this is how it works. You do send from this account.

    And, another possible reason is the From mail address itself. If you added it to your Google Mail account as one of your own addresses (and confirmed via test email with a link), then Google Mail will allow putting it onto From field. Otherwise it might drop it and replace it with the Sender.