1

(当收件人姓名包含括号时,我在使用 swift mailer 发送邮件时遇到问题)

示例代码:

$mail = new Swift_Message();
$mail->setTo('recipient@test.com', 'Recipient (bla bla)');
$mail->setFrom('sender@test.com', 'Sender');
$mail->setSubject('Test email');
$mail->setBody('<html><body><h3>Hello</h3></body></html>', 'text/html');
sfContext::getInstance()->getMailer()->send($mail);

如果收件人使用的是 gmail,他确实会收到电子邮件,但是当单击向下箭头以获取更多信息时,收件人:部分为空:

缺少:部分

问题是其他一些电子邮件服务没有收到该电子邮件。

至于原始消息内容,这里显示的细节太多了,但基本上我的问题是如何在不破坏任何内容的情况下使用括号。

4

1 回答 1

0

似乎 base64_encode 可以提供帮助,因此我修改了 swiftmailer 类SimpleMessage.php以确保每次都应用此修复程序。

从此修改 SimpleMessage:

public function setTo($addresses, $name = null)
{
  if (!is_array($addresses) && isset($name))
  {
    $addresses = array($addresses => $name);
  }

  if (!$this->_setHeaderFieldModel('To', (array) $addresses))
  {
    $this->getHeaders()->addMailboxHeader('To', (array) $addresses);
  }
  return $this;
}

对此:

public function setTo($addresses, $name = null)
{
  // if $name is set, encode it
  if(isset($name))
  {
    $name = $this->encodeName($name);
  }

  // if $addresses is an non numeric array (email => name), encode each name.
  if(is_array($addresses) && array_keys($addresses) !== range(0, count($addresses) - 1))
  {
    foreach($addresses as $key => $value)
    {
      $addresses[$key] = $this->encodeName($value);;
    }
  }

  if (!is_array($addresses) && isset($name))
  {
    $addresses = array($addresses => $name);
  }

  if (!$this->_setHeaderFieldModel('To', (array) $addresses))
  {
    $this->getHeaders()->addMailboxHeader('To', (array) $addresses);
  }
  return $this;
}

/**
 * Encode the name to avoid issues with some characters
 *
 * @param string $name
 * @return string
 */
private function encodeName($name)
{
  return "=?UTF-8?B?". base64_encode($name) . '?=';
}

这个答案帮助了我:Base64 encode from name for email

于 2013-06-21T18:52:54.230 回答