Mail on PHP

28 10 2009

Many people have posted about this before, but exactly because is a basic matter, is good to post my opinion on this subject.

About 4 years ago, I had to create a PHP code to send e-mail, but may lack of know how made me forget to make the mail function to work out. Besides, not everytime you can make such fixes on your server. This lead me to create the mail using sockets and sending commands to the smtp server of my preference.

In that time, hotmail, yahoo and gmail allowed the use of the smtp commands by telnet without worries. They hadn’t implemented at all the security protocols, like ssl or tls. That’s a good thing they had implemented security, of course. But,… and programming? What’s the difference now?

You cant say that the old code will still work out fine. It really can’t! if you try the correct commands on the telnet, all you’ll get is the client disconnection on the 3rd command sent to server. Fortunately, PEAR have a implementation of the SMTP protocol and have everything there to be used.

To install the package on your development machine, just type on the console (as a root if you are on linux)

  1. pear install Net_SMTP
  2. pear install Mail

Then its just to use some code like the one below:

require_once 'Mail.php';

class MyMail{
	private $to;
	private $from;
	private $subject = "Testando envio autenticado pelo Google";
	private $body = "Teste efetuado com sucesso!";
	private $host = "ssl://smtp.gmail.com";
	private $port = 25;
	private $username;
	private $password;
	public function getTo(){
		return $this->to;
	}
	public function setTo($t){
		$this->to = $t;
	}
	public function getFrom(){
		return $this->from;
	}
	public function setFrom($f){
		$this->from = $f;
	}
	public function getSubject(){
		return $this->subject;
	}
	public function setSubject($s){
		$this->subject = $s;
	}
	public function getBody(){
		return $this->body;
	}
	public function setBody($b){
		$this->body = $b;
	}
	public function getHost(){
		return $this->host;
	}
	public function setHost($h){
		$this->host = $h;
	}
	public function getPort(){
		return $this->port;
	}
	public function setPort($p){
		$this->port = $p;
	}
	public function getUsername(){
		return $this->username;
	}
	public function setUsername($un){
		$this->username = $un;
	}
	public function getPassword(){
		return $this->password;
	}
	public function setPassword($p){
		$this->password = $p;
	}
	public function send(){
		$headers = array ('From' => $this->getFrom(),
                            'To' => $this->getTo(),
                            'Subject' => $this->getSubject());

		$smtp = Mail::factory("smtp", array ('host' => $this->getHost(),
                                          'port' => $this->getPort(), // SMTPS(para mais detalhes ver /etc/services
                                          'auth' => true,
                                          'debug' => true, // Debug ligado
                                          'username' => $this->getUsername(),
                                          'password' => $this->getPassword())
		);
		$rc = $smtp->send($this->;to, $headers, $this->body);
		if(PEAR::isError($rc)){
			echo("<h1>Error " . $rc->getMessage(). "</h1>");
		} else {
			echo("Email enviado com sucesso!!");
		}
	}
}

It’s a preliminary class, so, many enhancements can be made to make the class better, but it just works as expected. Example to use? see below:

        if(isset($_POST)){
            require_once 'MyMail.class.php';
            $ms = new MyMail();
            $ms->setFrom('me@gmail.com');
            $ms->setTo('noone@gmail.com');
            $ms->setHost('smtp.google.com');
            $ms->setPort('25');
            $ms->setUsername('me@gmail.com');
            $ms->setPassword('p@ssw0rd');
            $ms->setBody('Test Message using PHP');
            $ms->setSubject('Test');
            $ms->send();
	}

This will produce the following stream to be sent to the server:

DEBUG: Recv: 220 mx.google.com ESMTP 23sm733843qyk.3
DEBUG: Send: EHLO localhost

DEBUG: Recv: 250-mx.google.com at your service, [189.70.93.58]
DEBUG: Recv: 250-SIZE 35651584
DEBUG: Recv: 250-8BITMIME
DEBUG: Recv: 250-STARTTLS
DEBUG: Recv: 250-ENHANCEDSTATUSCODES
DEBUG: Recv: 250 PIPELINING
DEBUG: Send: STARTTLS

DEBUG: Recv: 220 2.0.0 Ready to start TLS
DEBUG: Send: EHLO localhost

DEBUG: Recv: 250-mx.google.com at your service, [189.70.93.58]
DEBUG: Recv: 250-SIZE 35651584
DEBUG: Recv: 250-8BITMIME
DEBUG: Recv: 250-AUTH LOGIN PLAIN
DEBUG: Recv: 250-ENHANCEDSTATUSCODES
DEBUG: Recv: 250 PIPELINING
DEBUG: Send: AUTH LOGIN

DEBUG: Recv: 334 VXNlcm5hbWU6
DEBUG: Send: ZmFiaW8uY2VzYXIubWVkZWlyb3NAZ21haWwuY29t

DEBUG: Recv: 334 UGFzc3dvcmQ6
DEBUG: Send: ZG1hdGRtYXQwMQ==

DEBUG: Recv: 235 2.7.0 Accepted
DEBUG: Send: MAIL FROM:<sender-mail@gmail.com>

DEBUG: Recv: 250 2.1.0 OK 23sm733843qyk.3
DEBUG: Send: RCPT TO:<receiver-email@gmail.com>

DEBUG: Recv: 250 2.1.5 OK 23sm733843qyk.3
DEBUG: Send: DATA

DEBUG: Recv: 354  Go ahead 23sm733843qyk.3
DEBUG: Send: From: sender-email@gmail.com
To: receiver-email@gmail.com
Subject: Teste de e-mail

Teste de E-mail via Sockets
.

DEBUG: Recv: 250 2.0.0 OK 1256749304 23sm733843qyk.3
DEBUG: Send: QUIT

DEBUG: Recv: 221 2.0.0 closing connection 23sm733843qyk.3




Propel

7 04 2007

 

Bem, propel é um framework q se assemelha ao hibernate, fazendo Mapeamento Objeto Relacional. É muito interessante para que se possa desenvolver utilizando uma separação de camadas, como na figura abaixo:

Estilo de Desenvolvimento em Camadas com Propel

O propel fica responsável pela camada azul, de persistência. Serve basicamente para tornar tranparente o uso do banco de dados, como se estivéssemos chamando um método em um objeto.

Nesse post, a gente vai aprender a instalar o propel.

Uma coisa importante: Estou usando uma triad pra configurar apache, mysql e php, q é o XAMPP.

Na documentação do propel, se vê os pré requisitos: PEAR, Phing, Creole e PhpDocumentor;

O PEAR é um sistema de gerenciamento de “pacotes” para php. É bem interessante, e talvez valha outro post. O phing é um automatizador, como o GNU Make, ou o Ant. e o Creole tem a funcionalidade semelhante a um JDBC, promovendo uniformidade entre alguns bancos. O PhpDocumentor é um documentador

Com o php instalado e rodando, entre na linha de comando. Acesse o diretório do php, (no caso do XAMPP, é C:\Arquivos de Programas\xampp\php) e digite:

pear upgrade-all

para atualizar todos os pacotes da sua instalação do php. Isso não é necessário, mas é um bom momento para fazer.

Após isso, adicionamos dois novos “canais” que são como sites onde o PEAR pode procurar por pacotes. Fazemos isso com as seguinte linhas:

pear channel-discover pear.phing.info
pear channel-discover pear.phpdb.org

E para instalar, basta usar as seguintes linhas:

isso instalará o phing
pear install phing/phing<versão_mais_recente_do_phing>

isso instalará o creole
pear install

 

pear.phpdb.org/creole-1.1.0RC1
pear install pear.phpdb.org/jargon-1.1.0RC1

e por fim o propel
pear install pear.phpdb.org/propel_generator-1.2.0RC2
pear install pear.phpdb.org/propel_runtime-1.2.0RC2

Em breve, vou postar algo sobre como usar o propel.

Inté!