Sending emails with PHP

You can use PHP to send emails quite easily. All you have to do is install two modules and you are ready. You have to have php-pear installed on your machine. If it is not, then install it. Then you can install the needed modules Mail and Net_SMTP with


sudo pear install --alldeps Mail

It will also install Net_Socket and Auth_SASL which are not necessary but you may need them. For basic email send process Mail and Net_SMTP are sufficient. The sample code below shows how you can create a function that sends a message using SMTP server that accepts SSL connections.


<?php

require_once "Mail.php";
function general_email($message_subject,$message_body,$send_to) {
	$from = "Your Name ";
	$message = "DATE: ".date("l d.m.Y")." TIME: ".date("h:i:s A")."\r\n";
	$message .= utf8_decode($message_body);
	$host = "ssl://smtp.yourserver.com";
	$port = "465";
	$username = "your_username";
	$password = "your_password";
	$headers = array ('From' => $from,
	   'To' => $send_to,
	   'Subject' => $message_subject);
	 $smtp = Mail::factory('smtp',
	   array ('host' => $host,
	     'port' => $port,
	     'auth' => true,
	     'username' => $username,
	     'password' => $password));
	 
	 $mail = $smtp->send($to, $headers, $message_body);
	 
	 if (PEAR::isError($mail)) {
	   return("

" . $mail->getMessage() . "

"); } else { return("

Message successfully sent!

"); } } $recipient= "tux@antarctica.org"; $subject = "Test email"; $message = "This is a test. Do not reply."; general_email($subject,$message,$recipient); } ?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 99 other followers

Follow

Get every new post delivered to your Inbox.

Join 99 other followers

%d bloggers like this: