Wednesday, January 14, 2009

Send a mail using SMTP in PHP

1. First create a instance of smtp server.
$smtp_server = fsockopen("smtp.yourdomain.com", 25, $errno, $errstr, 30);

2. Check for errors while connecting to mail server.
if(!$smtp_server)
{
// We have an error, do something
exit;
}

3. Now write the headers in following way

fwrite($smtp_server, "HELLO\r\n");
fwrite($smtp_server, "MAIL FROM:\r\n");
fwrite($smtp_server, "RCPT TO:\r\n");
fwrite($smtp_server, "DATA\r\n");
fwrite($smtp_server, "Received: from yourdomain.com by anydomain.com ;\r\n");
fwrite($smtp_server, "Date: Thu, 03 Jan 2006 12:33:22 -0700\r\n");
fwrite($smtp_server, "From: Me \r\n");
fwrite($smtp_server, "Subject: Good Morning\r\n");
fwrite($smtp_server, "To: to@anydomain.com\r\n");
fwrite($smtp_server, "\r\nHi Dear:\r\nHow are you ?\r\n\r\n Me.\r\n");

4. Dont forget to write QUIT at the end.
fwrite($smtp_server, ".\r\nQUIT\r\n");

5. Close the connection.
fclose($smtp_server);

No comments: