This article introduces you to the issue of integrating PHP emails. PHP is one of the most popular web development programming languages today. Companies send emails to users to inform them of new products, such as promotional emails or to communicate with employees. Below I will give you a detailed introduction on how to integrate the popular Mailtrap platform in PHP to send multiple emails. I hope it will be helpful to friends in need~
Use Mailtrap to integrate PHP emails
PHP is one of the most popular web development programming languages today. Companies send emails to users to inform them of new products, such as promotional emails or to communicate with employees.
In this tutorial, we look at how to integrate the popular Mailtrap platform in our PHP to send multiple emails. [Recommended learning: PHP video tutorial]
Prerequisites
To follow this tutorial, you need to meet the following conditions.
Basic concepts of PHP, preferably PHP8.0.
Basic concepts of Simple Mail Transfer Protocol (SMTP).
A mailtrap account.
Goals
By the end of this tutorial, you should be able to integrate Mailtrap into your PHP application for testing emails.
Get started with mailtrap
Developing a wide range of applications has many requirements. This includes requirements to test your application to ensure everything is working as planned. One of the key requirements for these applications, such as Edge as a service, is the ability to test email functionality.
Co's customers often take advantage of Edge as a service, and they have a flexible payment plan. To remind these customers of their next due date, we need to send them an email.
A key challenge with sending emails is that we are not sure if our emails are being delivered. To ensure emails are delivered, we need to test our emails at a development and staging level to ensure they work well in production.
Now, Mailtrap comes along with the development and staging phases of the application development process. It is used to test emails to ensure they are delivered to their intended recipients. In the next section, we’ll take a closer look at PHP’s email sending methods, how they work, and the issues they may face.
PHP built-in email sending methods
In PHP, we have 2 different methods to send emails to our system users.
These methods are.
By using PHP packages, we will see in the next section.
Use built-in methods.
In this section, we will use PHP's mail() method to send emails to our users. We will then proceed to check whether these emails were delivered or failed.
The general structure of mail() is as follows.
// the mail method in PHP for sending emails mail( // recipient email string $to, // the email subject string $subject, // the email body string $message, //any other additional settings array|string $additional_headers = [], string $additional_params = "" ): bool
The above method receives multiple parameters, which are described below.
$to : This parameter refers to the recipient of the email. This can look like this: . test@section.io
$subject: This refers to the subject of the email, you must ensure that it complies with RFC 2047 - MIME (Multipurpose Internet Mail Extensions).
$message: This is the body of your email. We need to make sure each line is separated by CRLF (\r\n). The number of lines should not be greater than 70 characters, otherwise the email will not be sent.
$additional_headers (optional)- This is an array parameter that ensures we can add additional information to the email headers. This may include CC, BCC, etc.
Now that we understand the basic functionality of PHP’s mail() method, let’s move on to sending a sample email to some random emails.
<?php // sending to $to = 'no-reply@section.io'; // email subject $subject = "Section's Edge as a service"; // additional headers $headers = array( 'From' => 'test@example.com', 'Reply-To' => 'test2@example.com', 'X-Mailer' => 'PHP/' . phpversion() ); //body template $message = ' <html> <head> <title>Node.js Deployment</title> </head> <body> <p>I have a few requests:</p> <ol> <li>How much is the cost?</li> <li>What is the whole procedure of delpoyment</li> <li>How are my appplications distributed?</li> <li>How flexible is the payment plans?</li> </ol> </body> </html> '; mail($to, $subject, $message, $headers);
In the above code, we are sending a query email to a random email. We have defined the HTML body and added additional parameters such as title.
Note: It is important to remember that to send an email to a user using an HTML body, we must set our header as shown in the image below.
$headers[] = 'MIME-Version: 1.0'; $headers[] = 'Content-type: text/html; charset=iso-8859-1';
Otherwise, our email body will be delivered as HTML. Other issues can arise when our transport protocol encounters incorrect content. At this point, we assume that when this particular code is run, we expect it to run flawlessly.
However, how can we ensure that our emails are delivered to the intended recipients? In the next section, let's use a mail package to send the same email. These packages will help us overcome the limitations of the mail() method, which makes it quite difficult to check whether our mail has been delivered.
PHP Mail Package
A key drawback of the previous email sending method is that it has very limited features or functionality. This is usually a problem faced when you need to send large amounts of mail.
In this section we will look at how to overcome these shortcomings and subsequently analyze whether our emails are reaching their intended recipients.
We will discuss the following packages.
PHPMailer
Swift Mailer
Pear Mail
让我们继续,先从PHPMailer :PHPMailer是我们上面列出的所有包中最流行的用PHP发送邮件的包之一。
创建一个PHP文件mail.php ,并添加以下代码片段。
<?php // Import the mailer class use PHPMailer\PHPMailer\PHPMailer; require_once './vendor/autoload.php'; // create a new mailing object $mail = new PHPMailer(); // SMTP configuration $phpmailer = new PHPMailer(); $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.mailtrap.io'; $phpmailer->SMTPAuth = true; $phpmailer->Port = 2525; $phpmailer->Username = 'cb7xx33e1856xxx5b25xx'; $phpmailer->Password = '87f63xx87d73e52xxx4xx'; $mail->setFrom('no-reply@section.io', 'Node.js Deployment'); $mail->addAddress('test@gmail.com', 'Me'); $mail->Subject = 'Thanks for using section.io Edge as a service!'; // Our HTML setup $mail->isHTML(TRUE); $mail->Body = '<html>Hello johndoe, thank you for using our Node.js deployment and distribution platform. Kinldy check the document in the attachment below to review your payments plan.</html>'; $mail->AltBody = 'Success'; // adding mailing attachment for payment plan $mail->addAttachment('//node/paymments.pdf', 'payments.pdf'); // send the thank you messange if(!$mail->send()){ echo 'Your message could not be develired, try again later'; echo 'Error: ' . $mail->ErrorInfo; } else { echo 'Your message has been sent successfully.'; }
在上面的代码中,我们已经安装了PHPMailer包。我们还创建了这个类的一个新实例,$mail 。接下来,我们已经创建了我们的Mailtrap账户,并在这里抓取了凭证。
当你创建一个项目时,确保你将其与PHPMailer 选项集成,如下面的截图所示。
你会注意到,我们的截图省略了用户名和密码。这些是自动生成的,对每个用户都是不同的。
接下来,我们设置了我们的setFrom() 方法来接收发件人的电子邮件和电子邮件标题。然后,我们继续配置收件人的电子邮件地址和电子邮件的主题。
注意:之前,我们曾表示,我们可以将正文添加为HTML,然后适当地设置我们的内容类型。
在上面的邮件正文中,我们将信息定义为HTML,以便我们能够定制邮件,满足我们的要求。然后我们添加替代标签,再最后添加一个附件。然后,我们使用PHPMailer的$mail->send() 方法来发送我们的邮件。我们加入了if 语句来检查我们的邮件是否已经发送。
当我们的邮件未能送达时,我们通过打印一个警告信息来通知用户,否则就打印一个成功信息。让我们继续使用SwiftMailer ,实现同样的功能,如下所示。
在你的服务器上创建一个新的文件swift.php ,并添加以下代码片段。
<?php require_once './vendor/autoload.php'; try { // start by creating SMTP transport $transport = (new Swift_SmtpTransport('smtp.mailtrap.io', 2525)) ->setUsername('xxxxxxxxx') ->setPassword('xxxxxxxxx'); $swift_mailer = new Swift_Mailer($transport); // message creation $swift_message = new Swift_Message(); $swift_message->setSubject('Hooray! You just deployed your first Node'); swift_message->setFrom(['no-reply@section.io' => 'Saas']); $messswift_messageage->addTo('test@gmail.com','Test'); // Adding email attachment $email_attachment = Swift_Attachment::fromPath('./section/payments.pdf'); $swift_message->attach($email_attachment); // Set the plain-text part $swift_message->setBody('Hello John Doe, thank you for using the Section Node deployment service'); // Set the HTML part $swift_message->addPart('We are glad to welcome you on board'); // Send the message $res = swift_mailer->send($message); } catch (Exception $e) { echo $e->getMessage(); }
就像PHPMailer一样,我们首先安装这个包,并使用./vendor/autoload.php 路径导入它。还需要注意的是,根据你的系统设置,这个路径可能与你的应用程序路径不同。
接下来,我们将传输设置为使用我们Mailtrap的Swift_SmtpTransport 。拿起你的凭证,按照上面的代码设置。按照前面的步骤来配置你的应用程序,使其使用Mailtrap包来发送邮件。
现在,我们如何知道我们的邮件已经被送达?这就是我们使用Mailrap的原因。与PHPmail() 方法相比,该软件包允许我们配置我们的应用程序使用mailtrap,这给我们提供了一个平台来测试我们的应用程序,正如下一节所讨论的。
使用mailtrap测试电子邮件
登录你的Mailtrap账户,进入你的收件箱部分,如以下截图所示。
接下来,点击项目名称,展开你所发送的邮件。
注意:为了安全起见,上述截图上的一些功能已被跳过。
总结
在这篇文章中,我们已经广泛地讨论了PHP邮件方法的基本概念。我们已经看到了PHP内置的方法mail() 是如何限制我们发送带有测试功能的邮件的,我们已经用PHP包克服了这个问题。
作者:DebugUsery
链接:https://juejin.cn/post/7167615841398161416
The above is the detailed content of Let's talk about how Mailtrap integrates PHP emails. For more information, please follow other related articles on the PHP Chinese website!

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor