phpemailyii2swiftmailer

yii2 mailer how to not automatically use smtp gmail username as "From" Header


I built a website which has a contact form. I use yii2 mailer and smtp gmail setup for sending email. This is my smtp setup:

'host' => 'smtp.gmail.com',
'username' => 'websendmail1234@gmail.com',
'password' => 'mysecretpassword',
'port' => '587',
'encryption' => 'tls',
'streamOptions' => [ 
    'ssl' => [ 
        'allow_self_signed' => true,
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
],

And this is how I send the email in my controller:

Yii::$app->mailer->compose()
    ->setFrom(["myemail@gmail.com" => "My Name"])
    ->setTo(['henry.gunawan.1985@gmail.com' => 'Henry'])
    ->setSubject("The Subject")
    ->setHtmlBody("<html><body><h1>Hello</h1></body></html>")
    ->send();

It is sent successfully, but I check the email header and found this:

From: My Name <websendmail1234@gmail.com>

What I want is this:

From: My Name <myemail@gmail.com>

If I click reply, it will reply to websendmail1234@gmail.com which is the username of my smtp gmail setup instead of myemail@gmail.com

How can I use myemail@gmail.com in my From header?


Solution

  • According to this question you must set setFrom as indexed array and add setReplyTo call:

    Yii::$app->mailer->compose()
        ->setFrom(["myemail@gmail.com", "My Name"])
        ->setReplyTo('myemail@gmail.com')
        ->setTo(['henry.gunawan.1985@gmail.com' => 'Henry'])
        ->setSubject("The Subject")
        ->setHtmlBody("<html><body><h1>Hello</h1></body></html>")
        ->send();
    

    Also it's possible that Gmail itself allows to send from only for validated emails addresses and not random ones. Check here