Come inviare e-mail con testo/plain, text/html e attach in zf2? Io uso questo codice per inviare e-mail con SMTP:invia e-mail con file allegati in ZF2
$files = $this->params()->fromFiles();
$smtp = new \Zend\Mail\Transport\Smtp();
$smtp->setAutoDisconnect(true);
$optn = new \Zend\Mail\Transport\SmtpOptions(array(
'host' => 'mail.myserver.com',
'connection_class' => 'login',
'connection_config' => array(
'username' => '[email protected]',
'password' => 'mypassword',
),
));
$smtp->setOptions($optn);
$htmlPart = new \Zend\Mime\Part('<p>some html</p>');
$htmlPart->type = Mime::TYPE_HTML;
$textPart = new \Zend\Mime\Part('some text');
$textPart->type = Mime::TYPE_TEXT;
$i=0;
$attaches = array();
foreach($files as $file){
if ($file['error'])
continue;
$attaches[$i] = new \Zend\Mime\Part(file_get_contents($file['tmp_name']));
$attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
$attaches[$i]->encoding = 'base64';
$attaches[$i]->disposition = 'attachment';
$attaches[$i]->filename = $file['name'];
$i++;
}
$parts = array();
if (count($attaches)>0) {
$parts = array_merge(array($textPart,$htmlPart),$attaches);
$type = Mime::MULTIPART_MIXED;
}
else{
$parts = array($textPart, $htmlPart);
$type = Mime::MULTIPART_ALTERNATIVE ;
}
$body = new \Zend\Mime\Message();
$body->setParts($parts);
$message = new \Zend\Mail\Message();
$message->setFrom('[email protected]');
$message->addTo('[email protected]');
$message->setSubject('subject');
$message->setEncoding("UTF-8");
$message->setBody($body);
$message->getHeaders()->get('content-type')->setType($type);
$smtp->send($message);
Se allego file, invia i file e contenuti, ma mostra solo testo e HTML insieme nella casella di posta ricevente:
<p>some html</p>
some text
Quando don 't allegare nessun file, mostra il testo HTML singolarmente:
some html
Qualsiasi aiuto?
grazie. ma quando invio email a gmail con questo codice, gmail mostra il testo/tipo semplice nella pagina di posta elettronica. –
Sì, l'ho notato anche io. In qualche modo l'alternativa preferita dovrebbe essere l'ultima nell'array. Ho modificato la risposta. – tihe
@tihe potresti fornire un metodo per inviare più allegati ?? – GBRocks