Home Backend Development PHP Tutorial TP5 implements email sending service encapsulation and examples of sending attachments

TP5 implements email sending service encapsulation and examples of sending attachments

Oct 31, 2017 am 09:04 AM
send encapsulation Serve

The example of this article shares the specific code of the ThinkPHP5 package mail sending service for your reference. The specific content is as follows

1.Composer installs phpmailer

composer require phpmailer/phpmailer
Copy after login

2. Encapsulating the mail service class in ThinkPHP

I encapsulated it in the extend/Mail.php file in the extension directory. The content is as follows:

<?php
/**
* 邮件服务类
*/
class Mail extends \PHPMailer
{
  function construct()
  {
    date_default_timezone_set(&#39;PRC&#39;);             // 默认时区设置
 
    $this->CharSet = config(&#39;mail.charset&#39;);          // 邮件编码设置
    $this->isSMTP();                      // 启用SMTP服务
    $this->SMTPDebug = config(&#39;mail.smtp_debug&#39;);       // Debug模式级别
    $this->Debugoutput = config(&#39;mail.debug_output&#39;);     // Debug输出类型
    $this->Host = config(&#39;mail.host&#39;);             // SMTP服务器地址
    $this->Port = config(&#39;mail.port&#39;);             // 端口号
    $this->SMTPAuth = config(&#39;mail.smtp_auth&#39;);        // SMTP登录认证
    $this->SMTPSecure = config(&#39;mail.smtp_secure&#39;);      // SMTP安全协议
    $this->Username = config(&#39;mail.username&#39;);         // SMTP登录邮箱
    $this->Password = config(&#39;mail.password&#39;);         // SMTP登录密码
    $this->setFrom(config(&#39;mail.from&#39;), config(&#39;mail.from_name&#39;));      // 发件人邮箱和名称
    $this->addReplyTo(config(&#39;mail.reply_to&#39;), config(&#39;mail.reply_to_name&#39;)); // 回复邮箱和名称
  }
 
  /**
   * 发送邮件
   * @param [type] $toMail   收件人地址
   * @param [type] $toName   收件人名称
   * @param [type] $subject   邮件主题
   * @param [type] $content   邮件内容,支持html
   * @param [type] $attachment 附件列表。文件路径或路径数组
   * @return [type]       成功返回true,失败返回错误消息
   */
  function sendMail($toMail, $toName, $subject, $content, $attachment = null)
  {
    $this->addAddress($toMail, $toName);
    $this->Subject = $subject;
    $this->msgHTML($content);
     
    if($attachment) { // 添加附件
      if(is_string($attachment)){
        is_file($attachment) && $this->AddAttachment($attachment);
      }
      else if(is_array($attachment)){
        foreach ($attachment as $file) {
          is_file($file) && $this->AddAttachment($file);
        }
      }   
    }
 
    if(!$this->send()){ // 发送
      return $this->ErrorInfo;
    }
    else{
      return true;
    }
  }
}
Copy after login

Note:If you send an attachment, it is recommended to use the English path. Chinese paths may cause attachments to fail to be sent and emails received without attachments.

Some of the configuration parameters required above, I put them in the extension configuration directory application/extra/mail.php file, the content is as follows:

<?php
/**
 * 邮件服务相关配置
 */
return [
  &#39;charset&#39; => &#39;utf-8&#39;,         // 邮件编码
  &#39;smtp_debug&#39; => 0,           // Debug模式。0: 关闭,1: 客户端消息,2: 客户端和服务器消息,3: 2和连接状态,4: 更详细
  &#39;debug_output&#39; => &#39;html&#39;,       // Debug输出类型。`echo`(默认),`html`,或`error_log`
  &#39;host&#39; => &#39;smtp.126.com&#39;,       // SMTP服务器地址
  &#39;port&#39; => 465,             // 端口号。默认25
  &#39;smtp_auth&#39; => true,          // 启用SMTP认证
  &#39;smtp_secure&#39; => &#39;ssl&#39;,        // 启用安全协议。&#39;&#39;(默认),&#39;ssl&#39;或&#39;tls&#39;,留空不启用
  &#39;username&#39; => &#39;yourname@example.com&#39;, // SMTP登录邮箱
  &#39;password&#39; => &#39;yourpassword&#39;,     // SMTP登录密码。126邮箱使用客户端授权码,QQ邮箱用独立密码
  &#39;from&#39; => &#39;from@example.com&#39;,     // 发件人邮箱
  &#39;from_name&#39; => &#39;name&#39;,         // 发件人名称
  &#39;reply_to&#39; => &#39;&#39;,           // 回复邮箱的地址。留空取发件人邮箱
  &#39;reply_to_name&#39; => &#39;&#39;,         // 回复邮箱人名称。留空取发件人名称
]; 
Copy after login

Note: General Default port 25. If the security protocol ssl is used, the port number is usually 465 or 587. For example, 126 mailbox. It is recommended to use a secure protocol, because Alibaba Cloud servers prohibit port 25 of non-secure protocols.

For more configuration parameters, you can check out the source code: https://github.com/PHPMailer/PHPMailer/blob/master/class.phpmailer.php

3 .Test

In the method in the controller, add the test code:

public function mail()
{
  $mail = new \Mail;
  $ok = $mail->sendMail(&#39;xxxxxxxxx@qq.com&#39;, &#39;mingc&#39;, &#39;邮件来了&#39;, &#39;<p style="color: #f60; font-weight: 700;">恭喜,邮件成功!</p>&#39;, &#39;C:/Users/Administrator/Desktop/body.bmp&#39;);
  var_dump($ok);
}
  
Copy after login

Here I use 126 mailbox, security protocol ssl, port number 465, send html content, the test is successful:

The above is the detailed content of TP5 implements email sending service encapsulation and examples of sending attachments. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to Windows 10 Security Center service being disabled Solution to Windows 10 Security Center service being disabled Jul 16, 2023 pm 01:17 PM

The Security Center service is a built-in computer protection function in the win10 system, which can protect computer security in real time. However, some users encounter a situation where the Security Center service is disabled when booting the computer. What should they do? It's very simple. You can open the service panel, find the SecurityCenter item, then right-click to open its properties window, set the startup type to automatic, and then click Start to start the service again. What to do if the Win10 Security Center service is disabled: 1. Press "Win+R" to open the "Operation" window. 2. Then enter the "services.msc" command and press Enter. 3. Then find the "SecurityCenter" item in the right window and double-click it to open its properties window.

How to send files to others on TikTok? How to delete files sent to others? How to send files to others on TikTok? How to delete files sent to others? Mar 22, 2024 am 08:30 AM

On Douyin, users can not only share their life details and talents, but also interact with other users. In this process, sometimes we need to send files to other users, such as pictures, videos, etc. So, how to send files to others on Douyin? 1. How to send files to others on Douyin? 1. Open Douyin and enter the chat interface where you want to send files. 2. Click the &quot;+&quot; sign in the chat interface and select &quot;File&quot;. 3. In the file options, you can choose to send pictures, videos, audio and other files. After selecting the file you want to send, click &quot;Send&quot;. 4. Wait for the other party to accept your file. Once the other party accepts it, the file will be transferred successfully. 2. How to delete files sent to others on Douyin? 1. Open Douyin and enter the text you sent.

WhatsApp Tips: How to Send HD Photos and Videos WhatsApp Tips: How to Send HD Photos and Videos Sep 10, 2023 am 10:13 AM

WhatsApp has launched a new option that allows users to send photos and videos in high resolution through the messaging platform. Read on to find out how it's done. WhatsApp has released an update that allows iPhone and Android users to send photos and videos in high resolution, finally addressing the service's low-quality media sharing limitations. The option is called "HD Quality" and means users can send clearer photos and videos with minimal compression. For example, images captured on the iPhone can now be sent at 3024x4032 resolution instead of the previous maximum of 920x1280, while videos can be sent at 1280×718 resolution instead of 848×476.

How to open Remote Desktop Connection Service using command How to open Remote Desktop Connection Service using command Dec 31, 2023 am 10:38 AM

Remote desktop connection has brought convenience to many users' daily lives. Some people want to use commands to connect remotely, which is more convenient to operate. So how to connect? Remote Desktop Connection Service can help you solve this problem by using a command to open it. How to set up the remote desktop connection command: Method 1. Connect remotely by running the command 1. Press "Win+R" to open "Run" and enter mstsc2, then click "Show Options" 3. Enter the IP address and click "Connect". 4. It will show that it is connecting. Method 2: Connect remotely through the command prompt 1. Press "Win+R" to open "Run" and enter cmd2. In the "Command Prompt" enter mstsc/v:192.168.1.250/console

What is the correct way to restart a service in Linux? What is the correct way to restart a service in Linux? Mar 15, 2024 am 09:09 AM

What is the correct way to restart a service in Linux? When using a Linux system, we often encounter situations where we need to restart a certain service, but sometimes we may encounter some problems when restarting the service, such as the service not actually stopping or starting. Therefore, it is very important to master the correct way to restart services. In Linux, you can usually use the systemctl command to manage system services. The systemctl command is part of the systemd system manager

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to enable audio service in win7 How to enable audio service in win7 Jul 10, 2023 pm 05:13 PM

Computers have many system services to support the application of various programs. If the computer has no sound and most audio services are not turned on after troubleshooting hardware problems, how do you enable audio services in win7? Many friends are confused, so for the question of how to enable the audio service in win7, the editor below will introduce how to enable the audio service in win7. How to enable audio service in win7. 1. Find the computer on the computer desktop under Windows 7 system, right-click and select the management option. 2. Find and open the service item under Services and Applications in the computer management interface that opens. Find WindowsAudio on the service interface on the right and double-click to open the modification. 4. Switch to the regular project and click Start to enable the function.

How to get HTML form data as text and send to html2pdf? How to get HTML form data as text and send to html2pdf? Sep 06, 2023 pm 12:21 PM

html2pdf is a JavaScript package that allows developers to convert html to canvas, pdf, images, and more. It takes html as parameter and adds it to pdf or desired document. Additionally, it allows users to download the document after adding html content. Here we will access the form and add it to the pdf using the html2pdfnpm package. We will see different examples to add form data to pdf. Syntax User can follow the following syntax to pass html form data as text and send it to html2pdf. varelement=document.getElementById('form');html2

See all articles