I have authenticated domain . Now I want my users sending mail from that domain to able to choose the from_address of mail. They send mail within the domain using sendgrid, then the from address of the mail should be user’s own mail id. Mail reached to the receiver should be sent from the user themselves.
It is possible to achieve the scenario?
<?php
namespace AppServices;
use SendGrid;
use SendGridMailMail;
use IlluminateSupportFacadesLog;
class SendGridEmailService
{
public function sendEmail($to, $subject, $htmlContent, $fromEmail = null, $fromName = null)
{
try {
// Use authenticated domain from config
$fromEmail = $fromEmail ?? config('mail.from.address');
$fromName = $fromName ?? config('mail.from.name');
$email = new Mail();
$email->setFrom($fromEmail, $fromName);
$email->setSubject($subject);
$email->addTo($to);
$email->addContent("text/html", $htmlContent);
$response = $this->sendGrid->send($email);
// Log successful send
if ($response->statusCode() == 202) {
Log::info('Email sent successfully', [
'to' => $to,
'subject' => $subject,
'status' => $response->statusCode()
]);
return true;
}
// Log any unexpected response
Log::warning('Email send returned unexpected status', [
'status' => $response->statusCode(),
'body' => $response->body()
]);
return false;
} catch (Exception $e) {
Log::error('SendGrid Email Error: ' . $e->getMessage(), [
'to' => $to,
'subject' => $subject
]);
return false;
}
}
}
I have been trying to find the solution for so long in docs and other places. I really am looking forward to achieve this functionality.