Benutzer: Gast
Eintrag: Extbase 6+: sendMail

Extbase 6+: sendMail

von: marcel
Tags: Typo3, Extbase
Kreise: Typo3
Code: PHP
/**
 * send a mail with build-in swiftmailer
 * @param \mixed $to array(key1 => array('email' => 'name1@domain.tld', 'name' => 'Name1'), key2 => array('email' => 'name2@domain.tld', 'name' => 'Name2')) or just a string with the email-address
 * @param \string $subject
 * @param \string $html
 * @param \string $plain
 * @param \string $fromEmail
 * @param \string $fromName
 * @param \string $replyToEmail
 * @param \string $replyToName
 * @param \string $returnPath
 * @param \array $attachements array('path/to/file1.suffix' => 'nameOfFile1', 'path/to/file2.suffix' => 'nameOfFile2', 'path/to/fileX.suffix' => 'nameOfFileX')
 * @return \boolean true, if mail should be send - false, if parameter errors are given
 */
public static function sendMail($to, $subject, $html, $plain, $fromEmail = '', $fromName = '', $replyToEmail = '', $replyToName = '', $returnPath = '', $attachements = array()) {
  // make instance of swiftmailer
  $message = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
  
  // from
  if ($fromEmail) {
    $message->setFrom(array($fromEmail => $fromName));
  }

  // to
  $recipients = array();
  if (is_array($to)) {
    foreach ($to as $pair) {
      if (\TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($pair['email'], false)) {
        if (trim($pair['name'])) {
          $recipients[$pair['email']] = $pair['name'];
        } else {
          $recipients[] = $pair['email'];
        }
      }
    }
  } else {
    $recipients[] = $to;
  }

  if (!count($recipients)) {
    return false;
  }

  $message->setTo($recipients);

  // subject
  $message->setSubject($subject);

  // html
  $message->setBody($html, 'text/html', 'utf-8');

  // plain
  if ($plain) {
    $message->addPart($plain, 'text/plain', 'utf-8');
  }

  // returnPath
  if (trim($returnPath)) {
    $message->setReturnPath($returnPath);
  }

  // replyTo
  if (trim($replyToEmail) && \TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($replyToEmail)) {
    if (trim($replyToName)) {
      $message->setReplyTo(array($replyToEmail => $replyToName));
    } else {
      $message->setReplyTo(array($replyToEmail));
    }
  }

  // attachements
  if (count($attachements)) {
    foreach ($attachements as $file => $name) {
      if (file_exists($file)) {
        if (trim($name)) {
          $message->attach(Swift_Attachment::fromPath($file)->setFilename($name));
        } else {
          $message->attach(Swift_Attachment::fromPath($file));
        }
      }
    }
  }

  // send
  $message->send();

  return true;
}

Methode, um in Typo3 6.x mit SwiftMailer eine E-Mail zu versenden.

(1) Ganybhat Bhat schrieb am 21. 1. 2014 um 07:53 Uhr
Have to change
$message->attach(Swift_Attachment::fromPath($file)->setFilename($name));
to
$message->attach(\Swift_Attachment::fromPath($file)->setFilename($name));