Take “setFrom” name as in Gmail configuration using Swift Mailer

微笑、不失礼 提交于 2021-02-05 08:55:26

问题


I'm using Swiftmailer to send emails in Symfony project.

$msg = (new \Swift_Message("Subject"))
            ->setFrom('xxx123@gmail.com')
            ->setTo('yyy@gmail.com')
            ->setBody($mailContent);

In the received email, the name of Sender looks like xxx123. But the name for this email id in its configuration is XXX YYY.

I can use,

->setFrom('xxx123@gmail.com' => 'XXX YYY')

but, I don't want to set name directly in the code as it may be changed to something else like YYY ZZZ.

How can I achieve this? Thanks in advance!!


回答1:


Sender name is always set in the header of every message. So header can be set by any email client. Your SwiftMailer is also email client in this case.

Your email server can rewrite header but only in specific cases. Like Gmail rewrite all email addresses that you didn't validate in the account settings to your base email.

If you need to fetch your sender name from Gmail account you can use Gmail-API. Authenticate your application with OAuth and send GET request to url:

https://www.googleapis.com/gmail/v1/users/me/settings/sendAs/YOUR_EMAIL_ADDRESS

You will receive JSON like this:

{
 "sendAsEmail": "YOUR_EMAIL_ADDRESS",
 "displayName": "SENDER NAME THAT YOU NEED",
 "replyToAddress": "",
 "signature": "Your standard signature for emails created by Gmail in browser",
 "isPrimary": true,
 "isDefault": true
}

More about Google API for this request you can find here: https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs/get




回答2:


You can use this code:

$fromEmail = "xxx123@gmail.com";
$fromName = "Sender Name";

$msg = (new \Swift_Message("Subject"))
        ->setFrom([$fromEmail => $fromName])
        ->setTo('yyy@gmail.com')
        ->setBody($mailContent);

If you put only email, code will cut name from email until @. In your case it's: xxx123@gmail.com



来源:https://stackoverflow.com/questions/51356866/take-setfrom-name-as-in-gmail-configuration-using-swift-mailer

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