PHP

Inviare una mail

by Andrea Spera

PHP Mailer
PHPMailer è una libreria PHP che semplifica l'invio di email tramite codice. Fornisce un'interfaccia facile da usare per inviare email utilizzando protocolli come SMTP, supporta l'invio di allegati, email HTML, autenticazione, crittografia SSL/TLS e molto altro, rendendola una soluzione versatile rispetto alla funzione mail() nativa di PHP.
Codice
<?php
require_once('class.phpmailer.php');
require_once('class.smtp.php');
// personalizzare a seconda della posizione dei file
function myPhpMailer($to)
	{
	$mail = new PHPMailer(true);
	try
		{
		//Server settings
		$mail->SMTPDebug = 2;//Enable verbose debug output
		$mail->isSMTP();//Set mailer to use SMTP
		$mail->Host = 'smtps.xxxxxxxx';//SMTP server
		$mail->SMTPAuth = true;//Enable SMTP authentication
		$mail->Username = 'my user name';//SMTP username
		$mail->Password = 'xxxxxxxx';//SMTP password
		$mail->SMTPSecure = 'ssl';//'tls'/'ssl'
		$mail->Port = 465;//Port to connect to
		//Recipients
		$mail->setFrom('xxxxx@xxxxx.xx', 'My Name');//From
		$mail->addAddress($to);//Recipient, name is optional
		$mail->AddReplyTo('xxxxx@xxxxx.xx', 'My Name');//Reply to
		// Charset UTF-8
		$mail->CharSet = 'UTF-8';
		// Content
		$mail->isHTML(true);//Set email format to HTML
		$mail->Subject = 'Oggetto della mail';
		$mail->Body='
		<div>Corpo della mail</div>
		';
		$mail->AltBody = 'Testo alternativo, se non supportato HTML';
		$mail->SMTPDebug = 0;
		$mail->send();
		return true;
		}
	catch(Exception $e)
		{
		$mail->SMTPDebug = 0;
		return false;
		}
	}
$recipient="xxxxx@xxxxx.xx";
if(myPhpMailer($recipient)==TRUE)
	{
	// Mail inviata correttamente
	}
	else
		{
		// Errore
		}
?>
I file class.phpmailer.php e class.smtp.php sono facilmente reperibili in rete.
Per comodità metto a disposizione una cartella .zip contenente entrambi.
link per il download della cartella compressa