简体   繁体   中英

How to send email using gmail smtp server with first and last name in the "from" field?

I send emails using Gmail's SMTP server from "Account Beta" to "Account Alpha". When I created Account Beta I set the account's first name as "Account" and its last name as "Beta". Then I manually sent an email to Account Alpha and from it added Beta to Alpha's contacts, entering the same first and last name and even entering a nickname of "Account Beta".

If I manually send an email from Beta to Alpha, the "from" field shows "Account Beta" correctly. If I send it through code, however, it only displays the email of account beta.

This is my code:

        try
        {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("AccountBeta@gmail.com", "password"),
                EnableSsl = true
            };

            client.Send("AccountBeta@gmail.com", "AccountAlpha@gmail.com", subject, body);
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }

Of course subject and body are strings passed to the method and password is replaced by the actual password for AccountBeta@gmail.com . I'll bother myself with better security once this thing runs fine.

Replacing
client.Send("AccountBeta@gmail.com", "AccountAlpha@gmail.com", subject, body);
with
client.Send("Account Beta", "AccountAlpha@gmail.com", subject, body);

throws an exception that "Account Beta" isn't a valid email address.

How can I set it up so that emails sent from my code show as from "Account Beta" in Account Alpha's inbox?

You can do it by using the second overload of client.send which requires object of MailMessage

Here MailAddress requires parameter like MailAddress(fromEmail,displayName)



 try
 {
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("AccountBeta@gmail.com", 
               "password"),
                EnableSsl = true
            };

            var mailMessage = new MailMessage(new MailAddress("AccountBeta@gmail.com", "Account Beta"), new MailAddress("AccountAlpha@gmail.com"))
                {
                    Subject = subject,
                    Body = body,
                };

                client.Send(mailMessage); 
}
catch (Exception e)
{
            Console.WriteLine("An error occurred: " + e.Message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM