Home  >  Article  >  Backend Development  >  Let’s talk about how Mailtrap integrates PHP emails

Let’s talk about how Mailtrap integrates PHP emails

藏色散人
藏色散人forward
2022-11-23 16:45:006331browse

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~

Let’s talk about how Mailtrap integrates PHP emails

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      = &#39;no-reply@section.io&#39;;
// email subject
$subject = "Section&#39;s Edge as a service";
// additional headers
$headers = array(
    &#39;From&#39; => &#39;test@example.com&#39;,
    &#39;Reply-To&#39; => &#39;test2@example.com&#39;,
    &#39;X-Mailer&#39; => &#39;PHP/&#39; . phpversion()
);
//body template

$message = &#39;
<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>
&#39;;

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[] = &#39;MIME-Version: 1.0&#39;;
$headers[] = &#39;Content-type: text/html; charset=iso-8859-1&#39;;

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 &#39;./vendor/autoload.php&#39;;
// create a new mailing object
$mail = new PHPMailer();
// SMTP configuration

$phpmailer = new PHPMailer();
$phpmailer->isSMTP();
$phpmailer->Host = &#39;smtp.mailtrap.io&#39;;
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 2525;
$phpmailer->Username = &#39;cb7xx33e1856xxx5b25xx&#39;;
$phpmailer->Password = &#39;87f63xx87d73e52xxx4xx&#39;;

$mail->setFrom(&#39;no-reply@section.io&#39;, &#39;Node.js Deployment&#39;);
$mail->addAddress(&#39;test@gmail.com&#39;, &#39;Me&#39;);
$mail->Subject = &#39;Thanks for using section.io Edge as a service!&#39;;

// Our HTML setup

$mail->isHTML(TRUE);
$mail->Body = &#39;<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>&#39;;
$mail->AltBody = &#39;Success&#39;;
// adding mailing attachment for payment plan
$mail->addAttachment(&#39;//node/paymments.pdf&#39;, &#39;payments.pdf&#39;);
// send the thank you messange
if(!$mail->send()){
    echo &#39;Your message could not be develired, try again later&#39;;
    echo &#39;Error: &#39; . $mail->ErrorInfo;
} else {
    echo &#39;Your message has been sent successfully.&#39;;
}

在上面的代码中,我们已经安装了PHPMailer包。我们还创建了这个类的一个新实例,$mail 。接下来,我们已经创建了我们的Mailtrap账户,并在这里抓取了凭证。

当你创建一个项目时,确保你将其与PHPMailer 选项集成,如下面的截图所示。

Let’s talk about how Mailtrap integrates PHP emails

你会注意到,我们的截图省略了用户名和密码。这些是自动生成的,对每个用户都是不同的。

接下来,我们设置了我们的setFrom() 方法来接收发件人的电子邮件和电子邮件标题。然后,我们继续配置收件人的电子邮件地址和电子邮件的主题。

注意:之前,我们曾表示,我们可以将正文添加为HTML,然后适当地设置我们的内容类型。

在上面的邮件正文中,我们将信息定义为HTML,以便我们能够定制邮件,满足我们的要求。然后我们添加替代标签,再最后添加一个附件。然后,我们使用PHPMailer的$mail->send() 方法来发送我们的邮件。我们加入了if 语句来检查我们的邮件是否已经发送。

当我们的邮件未能送达时,我们通过打印一个警告信息来通知用户,否则就打印一个成功信息。让我们继续使用SwiftMailer ,实现同样的功能,如下所示。

在你的服务器上创建一个新的文件swift.php ,并添加以下代码片段。

<?php
require_once &#39;./vendor/autoload.php&#39;;
 try {
    // start by creating SMTP transport
    $transport = (new Swift_SmtpTransport(&#39;smtp.mailtrap.io&#39;, 2525))
        ->setUsername(&#39;xxxxxxxxx&#39;)
        ->setPassword(&#39;xxxxxxxxx&#39;);

    $swift_mailer = new Swift_Mailer($transport);

    // message creation
    $swift_message = new Swift_Message();

    $swift_message->setSubject(&#39;Hooray! You just deployed your first Node&#39;);

    swift_message->setFrom([&#39;no-reply@section.io&#39; => &#39;Saas&#39;]);
    $messswift_messageage->addTo(&#39;test@gmail.com&#39;,&#39;Test&#39;);

    // Adding email attachment
   $email_attachment = Swift_Attachment::fromPath(&#39;./section/payments.pdf&#39;);

    $swift_message->attach($email_attachment);

    // Set the plain-text part
    $swift_message->setBody(&#39;Hello John Doe, thank you for using the Section Node deployment service&#39;);
     // Set the HTML part
    $swift_message->addPart(&#39;We are glad to welcome you on board&#39;);
     // 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账户,进入你的收件箱部分,如以下截图所示。

Let’s talk about how Mailtrap integrates PHP emails

接下来,点击项目名称,展开你所发送的邮件。

Let’s talk about how Mailtrap integrates PHP emails

注意:为了安全起见,上述截图上的一些功能已被跳过。

总结

在这篇文章中,我们已经广泛地讨论了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!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete