PHP mail() and PHPMailer

Rayj00

New member
I am saving a form content to a DB as well as sending the contents of the form using PHP mail() and HTML.
I am using msmtp as the MTA. (smtp.gmail.com) This works fine.

Now I want to send an additional email with an attachment. In this case I want to use PHPMailer.
Not being a seasoned developer, most install instructions include Composer. I'd rather install without Composer,
which I did. But can anyone now provide a simple configuration to use for attachments?

Thanks,

Ray
 
Certainly! Without using Composer, you can still utilize PHPMailer to send emails with attachments.

  1. Download PHPMailer: First, download PHPMailer from its GitHub repository. You can download the latest version as a zip file from here.
  2. Extract PHPMailer: Once downloaded, extract the contents of the zip file to your project directory. You'll see a folder named something like PHPMailer-x.y.z, where x.y.z represents the version number.
  3. Include PHPMailer Class: In your PHP script where you want to send the email with an attachment, include the PHPMailer class file. Assuming you extracted PHPMailer to a folder named PHPMailer-x.y.z, and your script is in the same directory:

PHP:
require 'PHPMailer-x.y.z/src/PHPMailer.php';
require 'PHPMailer-x.y.z/src/SMTP.php';
require 'PHPMailer-x.y.z/src/Exception.php';

Configure PHPMailer: Set up PHPMailer with your SMTP settings and other necessary configurations.

PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@gmail.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('your_email@gmail.com', 'Your Name');
$mail->addAddress('recipient@example.com', 'Recipient Name');
$mail->isHTML(true);
$mail->Subject = 'Subject of the Email';
$mail->Body = 'Body of the Email';

Add Attachment: To attach a file, use the addAttachment() method:

PHP:
$file_path = '/path/to/your/attachment.pdf'; // Path to the attachment
$mail->addAttachment($file_path, 'filename.pdf'); // Adjust filename as needed

  1. Send Email: Finally, send the email:
    PHP:
    if (!$mail->send()) {
    echo 'Error: ' . $mail->ErrorInfo;
    } else {
    echo 'Email sent successfully!';
    }
This is a basic setup to send emails with PHPMailer without using Composer. Make sure to replace 'your_email@gmail.com', 'your_password', 'recipient@example.com', and file paths with your actual values. Also, ensure that the file you want to attach exists and that you have appropriate permissions to access it.

Best Regard
Danish Hafeez | QA Assistant
ICTInnovations
 
Back
Top