JIYIK CN >

Current Location:Home > Learning > PROGRAM > PHP >

Sending attachments in emails using PHP

Author:JIYIK Last Updated:2025/04/12 Views:

We will look at different ways to send attachments via email in PHP.


PHPMailerSend attachments in email using

We can use PHPMailerthe SendEmail class to send emails, allowing us to send attachments. We can create an PHPMailerobject of the SendEmail class and use its methods and properties to send emails to the desired recipients. We will use Gmail's SendEmail. Therefore, we will use SMTPthe SendEmail protocol. The library has addAttachment()a SendEmail method that allows us to add attachments. First, we need to download the library from GitHub .

For example, create a folder srcand copy three files PHPMailer.php, , SMTP.phpand Exception.phpinto it. Then create a file index.phpand use requirethe statement to include the three files. Then use the corresponding classes of these files. Next, create PHPMailer()an object of the class $mail. Use the Usernameand Passwordproperties to set the sender's email and password. Use the Subjectand Bodyproperties to set the subject and body of the email. Use addAttachment()the function to add an attachment. Pass the relative path of the attachment as a parameter to the method. AddAddress()Write the recipient's email in the method. Finally, call Send()the method to send the email. Next, call to smtpClose()close SMTPthe connection.

We need to change the sender's email to PHPMaileruse Gmail in . We should open the access option in Gmail 不太安全的应用程序to use PHPMailer. Then, running the following script will send an email and attachment to the recipient.

Sample code:

<?php
require 'src/PHPMailer.php';
require 'src/SMTP.php';
require 'src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = "true";
$mail->SMTPSecure ="tls";
$mail->Port = "587";
$mail->Username = "sendersemail@gmail.com";
$mail->Password = "password";

$mail->SetFrom('sendersemail@gmail.com');
$mail->Subject = 'Message Subject';
$mail->Body = "This is a body text";
$mail->addAttachment('attachments/project.pdf');
$mail->AddAddress( 'receiversmail@gmail.com' );

$mail->Send();
$mail->smtpClose();
?>

SwiftMailerSend attachments in email using

We can also use a third-party library SwiftMailerto send emails with attachments. This library provides a attach()method to add attachments while sending an email. We can install the library using the following command.

composer require "swiftmailer/swiftmailer:^6.0"

autoloader.phpWe need to include the file to use in our script SwiftMailer. This file is 供应商inside the folder where the file was downloaded. We will be using Gmail to send the email. To use Gmail, we need to use SMTPthe protocol. Therefore, we need to Swift_SmtpTransportcreate a transport using the class to set the host, port number, and protocol. We can set the sender's email and password using the transport. Swift_MailerThe class allows us to set the transport, while Swift_Mailerthe class allows us to set the message, recipients, and attachments.

autoload.phpFor example, the file in the working file is required to be vendor/autoload.php. Create Swift_SmtpTransportan object of the class $transportand set the host to smtp.gmail.com, the port number to 587, and the security protocol to tls. Then set the sender's email and password using the setUsernameand methods. Next, create an object of the class and set the object to it. Then, create another object of the class and write the subject as a parameter. Specify the sender's email and the recipient's email using the and methods. Write the email body in the method. Then, specify the attachment path using the method of the class using the . Finally, send the email using the object we created using the method. Provide the object as a parameter to the method.setPasswordSwift_Mailer$mail$transportSwift_Message$contentsetFrom()setTo()setBody()attach()Swift_AttachmentfromPath()$mailsend()$contentsend()

SwiftMailerThis is how we can send an email with an attachment using the library in PHP .

Sample code:

require_once 'vendor/autoload.php';

$transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
->setUsername('sendersemail@gmail.com')
->setPassword('password')

$mail = new Swift_Mailer($transport);
$content = (new Swift_Message('Subject'))
->setFrom(['sendersemail@gmail.com' => 'Senders Name'])
->setTo('recieversemail@gmail.com')
->setBody('This is a text')
->attach(Swift_Attachment::fromPath('attachments/project.pdf'));

$result = $mail->send($content);

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial