Mailgun “On behalf of” issue
We all know the feeling when we release a new project, we are overexcited until the first email goes out…
All of a sudden a client informs you, “Hey, the email I received has a strange “from” address. Can you fix it?“…
What is happening?
Even though we’ve registered our domain with Mailgun, made sure the correct DNS records are in place. And in our application, we’re using the correct API key combined with the domain and optionally the specific server that we prefer.
The “from” address in the email appears to be info=example.com@mg.example.com on behalf of info@example.com. which isn’t the address we wanted it to be, ideally it should be info@example.com
Mail::send(['html' => 'emails.template'], $data, function($message) use ($subject, $user){
$message->to($user->email, $user->name);
$message->subject("$subject");
$message->from("info@example.com");
});
This issue is caused by the fact that we are using another domain, a subdomain, to configure Mailgun. This is advised, otherwise, we would endanger the normal mail functionality of the domain, if there are any in place, such as Google Workplace or Office 365.
It is the mismatch between the domain used to send our email (mg.example.com) and the domain indicated as the “from” address in our app (example.com).
Mailgun’s suggestion
Mailgun suggests a solution on its website. You can find it here.
The suggested solution may endanger the normal mail functionality as described above. Because we would overwrite the SPF record on the main domain. Which isn’t ideal.
A quick and easy solution
In Laravel, we can specify the sending domain in the email headers. For this, we can use the ->sender
attribute.
Mail::send(['html' => 'emails.template'], $data, function($message) use ($subject, $user){
$message->to($user->email, $user->name);
$message->subject("$subject");
$message->from("info@example.com");
$message->sender("info@example.com");
});
By doing so we enforce the email sending address and the visible “from” address to be the same.
There, the job is done. Happy customer.
#mailgun, #tutorial