I've got a small function that implements use of Swift_Mailer
to handle sending emails:
public function send(string $subject, $to, string $msg, $from = '')
{
if (!empty($to)) {
if (empty($from)) {
$smtpSettings = $this->loadSettings();
$from = [$smtpSettings['from_email'] => $smtpSettings['from_name']];
}
var_dump($to);
$email = (new \Swift_Message($subject))
->setFrom($from)
->setTo($to)
->setBody($msg);
// Send the message
$result = $this->swift->send($email);
} else {
var_dump('nein');
}
}
Which gets used here:
$mailer->send(
'Some Subject',
[$email],
'Hello, world'
);
This returns this message:
0: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
After a quick Googles, it seems the Swift_Message
instance isn't getting the $to
value properly.
I added the var_dump($to)
to the script to see what's actually in it, and I get:
array(1) {
string(19) "someemail@domain.com"
}
The email above is psuedo for my real email, which I copy/pasted into thunderbird and sent an email to - all good, so I know the email is valid.
However, the error message seems to show that no email was passed. My code more or less mirrors the documentation but for some reason, my email isn't getting passed.
Does Swift_Message
have some weird scope issues? It doesn't seem like $subject
or $from
are going wrong, so why is the $to
potentially not in-scope?
AbraCadaver led me towards the right path, more so than the error message returned to me.
I copied the original code from the documentation and replaced the values one-by-one with the corresponding $var
, all worked, even $to
- the message was a red herring.
The $from
variable however, is what broke the script. The value was incorrectly formatted, fixing the format fixed the script.
I set $from
to ['theemail@domain.com' => 'Some Name']
and all was well.