How to send an html email using smtp in php?

by jasen_gottlieb , in category: Third Party Scripts , 20 days ago

How to send an html email using smtp in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 20 days ago

@jasen_gottlieb 

To send an HTML email using SMTP in PHP, you can use the PHPMailer library for sending emails. Here is an example code snippet on how to send an HTML email using SMTP in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;

// Create a new PHPMailer object
$mail = new PHPMailer();

// Set SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.yourmailserver.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-smtp-username';
$mail->Password = 'your-smtp-password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

// Set email content
$mail->isHTML(true);
$mail->Subject = 'Subject of the email';
$mail->Body = '<html><body><h1>Hello, This is a HTML email.</h1></body></html>';
$mail->AltBody = 'This is the plain text version of the email';

// Set sender and recipient email addresses
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');

// Send the email
if($mail->send()) {
    echo 'Email sent successfully';
} else {
    echo 'Error sending email: ' . $mail->ErrorInfo;
}
?>


Make sure to replace 'path/to/PHPMailer/src/PHPMailer.php', 'path/to/PHPMailer/src/SMTP.php', 'smtp.yourmailserver.com', 'your-smtp-username', 'your-smtp-password', 'Subject of the email', '[email protected]', and '[email protected]' with your actual values.


You can download PHPMailer library from GitHub: https://github.com/PHPMailer/PHPMailer


Hope this helps! Let me know if you have any questions.