How Can We Help?

< Back
You are here:
Print

How to send an email using PHPMailer?

296 Upvotes | 34 comments

PHPMailer is a code library and used to send emails safely and easily via PHP code from a web server. Sending emails directly via PHP code requires a high-level familiarity with SMTP standard protocol and related issues and vulnerabilities about Email injection for spamming. PHPMailer simplifies the process of sending emails and it is very easy to use.

Installation: The best way to install PHPMailer is by using the composer. Before proceeding makes sure to install the composer.

 

  • Open the Command prompt and go to the directory of the project in which you want to use PHPMailer.
  • Run the following command:
  • composer require phpmailer/phpmailer

 

Or you can download Phpmailer and place the two necessary files on your server:

  • class.phpmailer.php
  • class.smtp.php

Then, include the library and instantiate a PHPMailer object

require_once('path/to/library/class.phpmailer.php');
$mail = new PHPMailer();

Next, set up the object to use SMTP and configure it to point to the Mail250s server.

$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.swipemail.in";
$mail->Port = 2525;
$mail->Username = "mail250_username";
$mail->Password = "mail250_smtp_password";

Finally, set the properties for the particular email you want to send:

$mail->SetFrom('[email protected]', 'Web App');
$mail->Subject = "A Transactional Email From Web App"; $mail->MsgHTML($body);
$mail->AddAddress($address, $name);

Once everything is set up the way you want it, you call the object’s Send method. If the Send method returns true, then everything worked. If it returns false, then there was a problem.

if($mail->Send()) {
echo "Message sent!";
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

PHPMailer Object

$mail = new PHPMailer //Creates the new object.
$mail->From() //Sets the From email address for the message. Default value is root@localhost.
$mail->FromName() //Sets the From name of the message. Default value is Root User.
$mail->addAddress() //Recipient’s address and name.
$mail->addReplyTo() //Address to which recipient will reply.
$mail->AddAttachment() //To add attachment.
$mail->isHTML(true/false) //Send HTML or plain text email.$mail->Subject //Subject of the mail.
$mail->body //Body of the mail.
$mail->AltBody //Used to display plain text message for those email viewers which are not HTML compatible.$mail->send() //Sends the mail.
$mail->ErrorInfo //Displays errors if any.
$mail->setLanguage() //To display error messages in some other language.

 

For example, to use Russian, we write $mail->setLanguage(“ru”).

Table of Contents
Menu