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




First (?) Announcement of Windows 7 Failure

8 09 2009

Today on twitter, @lauromoura has tweet a report about a Windows 7 failure. See the link:

http://seclists.org/fulldisclosure/2009/Sep/0039.html

Worth to see, what Steve Ballmer said on Vista’s release and the press opinions: here.

Fact: no Windows (and no Operating System) will be totally secure. It’s all just a matter of time.





MCTS: SQL Server 2005

16 06 2009

Bem, um pouquinho tarde, mas enfim, passei nesse sábado na prova 70-431: Microsoft SQL Server 2005 – Implementation and Maintenance, inaugurando a minha intenção de me especializar em banco de dados.

A prova é composta de duas partes, uma com 35 questões objetivas, e outra com 12 questões de simulação. A parte objetiva é bem tradicional, e pelo menos as questões que foram selecionadas na minha prova foram bem distribuídas nos assuntos. Houveram questões de XML, de desenvolvimento com CLR, backup/restore, … acho que só não caiu de Service Broker. Na parte prática, tive sorte e das 12 questões, 4 foram sobre backup/restore (para configurar um backup de acordo com algumas características pedidas).

Agora é estudar pra atualizar pra MCTS: SQL Server 2008!





Microsoft Experience

18 04 2009

Bem, parece que estou começando a descobrir alguns outros projetos para aprendizado da Microsoft Brasil.

Hoje descobri o Microsoft Experience, que é similar aos programas Desenvolvedor 5 Estrelas (MSDN) [3] e Profissional 5 Estrelas (TechNet) [4], com conteúdo ministrado em vídeo por especialistas em várias tecnologias e provas a serem realizadas on-line. Os cursos disponíveis são os seguintes:

TechNet Experience:

  • Colaboração e Produtividade
  • Windows Vista
  • SQL / BI
  • Suporte Nível 1
  • Suporte Nível 2
  • Windows Server 2008
  • Segurança
  • InfraWeb

MSDN Experience

  • Office Development
  • SQL Server
  • Visual Studio Team System
  • Web Development

Já começei o meu curso de SQL Server hoje, e já passei na primeira prova. Acho que não vou ficar só nisso, e recomendo que vc faça o mesmo!

[1] TechNet Experience – http://technet.microsoft.com/pt-br/events/cc716281.aspx

[2] MSDN Experience – http://msdn.microsoft.com/pt-br/dd366110.aspx

[3] Desenvolvedor 5 Estrelas – http://www.mslatam.com/brasil/dce/

[4] Profissional 5 Estrelas – http://technet.microsoft.com/pt-br/events/tn.cincoestrelas.aspx





Powershell.com Videos

16 04 2009

PowerShell.com is promoting some videos ‘bout Windows PowerShell there are very interesting to see. Is a list of five videos (the fifth is in being built still) that shows the use of PowerShell into some environments that Microsoft had integrated with. Here’s the list:

  1. Getting To Know PowerShell;
  2. PowerShell for Active Directory;
  3. PowerShell for Exchange Server 2007;
  4. PowerShell for SQL Server 2008;
  5. PowerShell for Windows Servers & Clients.

Worth to see! [here to go]





Sharepoint update

17 02 2009

This week I was assigned to Install MOSS (Microsoft Office SharePoint Services) 2007 over WSS (Windows SharePoint Services) 3.0.

The thing i’ve never thought it would be a trouble was the fact that my WSS was english and my MOSS was Portuguese. When I installed MOSS, over WSS, it all look like that was ok, but, when any item of a list went to be edited, the feature was broken. It repeated in all other sites, in all other lists.

To make it useful again, I’ve deactivated the Spell Checker Service. It’s a workaround, and doesn’t solve the problem. When a feature of MOSS 2007 is seen, the name is messy.

Solution: Install the Language Pack feature.

Update: The language pack really makes some critical features to work, but doesn’t solve all the problems. If you are going to create a new site part, you’ll see that the web part names are all messy. In a lack of a better solution, backup all the sites, uninstall SharePoint, install it again correctly, then restore again the sites. This really is gonna work.





SharePoint Videos

29 01 2009

I’ve found today a set of videos which explains Microsoft Office SharePoint Services 2007 and Windows SharePoint Services 3.0 in very high detail. Each link goes to a module, which has many videos and demos that are presented by some guy from SharePoint Team.

If you are going to see them, you’ll need very very much time. Each module is very long (hour, hours), but exactly by this and the content, it’s worth to see.

Module 1: Microsoft Products and Technologies Server Farm Architecture

Module 2: Configuring SharePoint Server Farms (Overview)

Module 3: Securing Microsoft SharePoint Products and Technologies Server Farms

Module 4: Capacity Planning for SharePoint Server Farms

Module 5: Configuring Caching, IIS Compression, and Other Performance Options for SharePoint Server Farm

Module 6: Backup, Restore, High Availability, and Disaster Recovery for SharePoint Server Farms

Module 7: Microsoft SharePoint Technologies Operations

Module 8: Search Architecture and Configuration for SharePoint Server Farms





Dir by file age

28 01 2009

This is a simple tip. Sometimes is needed to select files in a folder by it’s age. Then (as far as I could see) the dir command can’t do this by a simple command line. I’ve written then a script that can do this by filtering a dir result:


function Get-TodayFiles{
    $day = New-Object System.TimeSpan(1,0,0,0,0)
    $today = Get-Date
    $result = New-Object System.Collections.ArrayList
	for($i = 0; $i -lt $files.Length; $i++){
        if ($today.Subtract($files[$i].LastWriteTime).CompareTo($day) -eq -1) {
            $result.Add($files[$i].FullName)
        }
    }
    return $result
}

This is a very programmer solution. PowerShell.com has made a new solution, easier than mine.

 Filter Select-FileAge {
       param($days)
       # is it a folder? Then omit:
       If ($_.PSisContainer) {
              # do not return folders effectively filtering them out
       } ElseIf ($_.LastWriteTime -lt (Get-Date).AddDays($days * -1)) {
              $_
       }
} 

This new one is used as a filter to the dir command, and is used in this way:

dir $env:windir *.log | Select-FileAge 20





Emails e Powershell

14 01 2009

Para algumas tarefas de manutenção, é chato estar indo nas máquinas e verificando se as tarefas estão sendo realmente feitas. Imagine por exemplo se você tem alguns servidores diferentes pra ficar monitorando algumas vezes no mês ou na semana. É incômodo ir fazendo Remote Desktop na máquina 1, ver o que tem de ser visto, deslogar, e assim por diante.

Um workaround para isso pode ser o envio de e-mails qnd a tarefa for concluída, com algum feedback se a tarefa foi feita com sucesso ou não.

Com o código abaixo, podemos enviar e-mails a partir de um script PowerShell. Este código é um ajuste com relação ao script postado em [1], adicionando as credenciais, e dando forma de função.

function Send-Mail{
	param([string]$to, [string]$subject, [string]$body)
	$smtp = New-Object System.Net.Mail.SmtpClient("your server here");
	$mailMessage = New-Object System.Net.Mail.MailMessage;
	$credential = New-Object System.Net.NetworkCredential("sender username", "sender password", "sender domain");
	$mailMessage.From = "sender mail";
	$mailMessage.To.Add($to);
	$mailMessage.Subject = $subject;
	$mailMessage.Body = $body;
	$smtp.Credentials = $credential;
	$smtp.Send($mailMessage);
}

 

[1] http://www.searchmarked.com/windows/how-to-send-an-email-using-a-windows-powershell-script.php

[2] http://www.brokenhaze.com/article.php?story=20080228214713878

[3] Windows Powershell





Verificador de Drivers do Vista / Vista Driver Verifier

12 01 2009

Recebi hoje uma dica[1] muito interessante. Muitos dos problemas que ocorrem com o Windows Vista podem vir em decorrência de problemas com drivers de terceiros que estão instalados para fazer seus dispositivos funcionarem.

Alguns desses drivers não são certificados pela Microsoft, ou porque as fabricantes de drivers não tem interesse ou por alguma questão de mercado.

Para isso, o Windows 2000, XP e o Vista (no 2008 Server também) foi inserido o utilitário Driver Verifier Manager[2], que realiza testes nos drivers instalados para ajudar no ajuste de problemas. Os testes consistem em detecção de chamadas ilegais de funções ou ações que podem corromper o sistema. Vale a pena dar uma olhada e fazer um teste.

===================================================

Today I received a tip [1] very interesting. Many of the problems that occur with Windows Vista may be due to problems with third-party drivers that are installed to make their devices work.

Some of these drivers are not certified by Microsoft, or because the manufacturers of drivers has no interest or any questions of the market.

For this, Windows 2000, XP and Vista (also in 2008 Server) was inserted as utility, the Driver Verifier Manager [2], which performs tests on the drivers installed to help problems troubleshooting. The tests are to detect illegal function calls or actions that might corrupt the system. It is worth taking a look and do a test.

 

[1] http://ct.techrepublic.com.com/clicks?t=73528218-d924b6aea9a40bf26b0cf90102af1b94-bf&brand=TECHREPUBLIC&s=5

[2] http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/VistaVerifier.doc