Home Backend Development PHP Tutorial 如何使用PHP通过SMTP发送电子邮件_PHP

如何使用PHP通过SMTP发送电子邮件_PHP

Jun 01, 2016 pm 12:29 PM
use send how e-mail pass mail

SMTP

由于PHP没有提供现成的smtp函数,却提供了一个功能不甚灵活的mail()函数,这个函数需要服务器配置上的支持,并且不支持smtp验证,在很多场合无法正常的工作,因此不建议使用。本文的目的在于为新手指明方向,并没有涉及那些高级的内容,一来本身水平有限,二来也担心不能准确的讲述相关的概念,进而对各位造成误导,还请自行深入学习。

  “使用php发送mail”最近已经成为继“register_globals”以后本版第二个新手陷阱,今天特地写这篇文章为新手解惑,希望可以为迷茫的人指明方向。

  让我们先从以下这个例子开始说起:

  引用:

[root@server~/]# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 server.domain.com.br ESMTP Postfix (2.1.0)
MAIL FROM: teste@dominio.com.br
250 Ok
RCPT TO: teste@dominio.com.br
250 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
teste
.
250 Ok: queued as 7B41F4665A
QUIT
221 Bye
Connection closed by foreign host.

  注:以上来自netkiller的postfix文档,偷懒,直接用现成的。

  首先是使用telnet来连接本地的25端口,稍微熟悉点网络的人都知道smtp协议使用25端口,这也就是说,现在在连接本地的smtp服务器。

  引用:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 server.domain.com.br ESMTP Postfix (2.1.0)

  这些东西是系统输出信息,说明已经连接上了,而且这个smtp服务器是postfix做的。

  “MAIL FROM: teste@dominio.com.br”这个命令指明了发件地址是teste@dominio.com.br,“250 Ok”说明这条命令被服务器接受并正确执行,这类似http协议的200、404、500等状态代码。接下来的“RCPT TO: teste@dominio.com.br”指明了收件地址是teste@dominio.com.br。

  引用:

DATA
354 End data with <CR><LF>.<CR><LF>
teste
.

  这一段是输入邮件正文,输入“DATA”以后系统提示使用“<回车>.<回车>”来结束输入,正文内容是“teste”。

  最后使用“QUIT”退出。

  以上就是最简单的一次发送mail的过程,从这个例子我们可以看出,发送mail其实是很简单的事情,实质上也就是建立一个对smtp服务器的连接,然后发送一些简单的命令给它,一封内容简单的邮件就发送出去了,至于更加复杂内容的邮件或者操作,其实也就是在此基础上稍加扩展而已。

  把这个过程用php来实现,其实就是利用php的Socket functions、Network Functions等等操作socket的函数来和smtp服务器建立一个连接,然后发送文本的命令给服务器,如果你亲自去看看那些写好的利用smtp协议发送邮件的类或者函数,相信可以印证我的说法。

由于已经存在很多现成的封装得很好的类或者函数替我们完成底层的socket级操作,我们只需要直接拿来用就好,而我也不会费时费神的在本文里去讨论底层的代码,有精神去研究的话,自己找代码来研究吧。现在继续跟我走,我们来点实际的代码来说明如何使用php发送邮件,采用的类是PEAR::Mail。

  代码:

<?php
 require_once 'Mail.php';

 $conf['mail'] = array(
   'host' => 'xx.xx.xx.xx', //smtp服务器地址,可以用ip地址或者域名
   'auth' => true, //true表示smtp服务器需要验证,false代码不需要
   'username' => 'tester', //用户名
   'password' => 'retset' //密码
 );

 /***
 * 使用$headers数组,可以定义邮件头的内容,比如使用$headers['Reply-To']可以定义回复地址
 * 通过这种方式,可以很方便的定制待发送邮件的邮件头
 ***/
 $headers['From'] = 'tester@domain.com'; //发信地址
 $headers['To'] = 'tester@domain.com'; //收信地址
 $headers['Subject'] = 'test mail send by php'; //邮件标题
 $mail_object = &Mail::factory('smtp', $conf['mail']);

 $body = <<< MSG //邮件正文
 hello world!!!
 MSG;

 $mail_res = $mail_object->send($headers['To'], $headers, $body); //发送

 if( Mail::isError($mail_res) ){ //检测错误
  die($mail_res->getMessage());
 }
?>


  以上的代码非常的简单,配合注释应该不难看懂,关于PEAR和PEAR::Mail的更多信息,可以自己去翻阅PEAR Manual得到进一步的信息。

  现在你依葫芦画瓢已经可以开始工作了,不过如果你还想做得更好、做得更多的话,我在这里提供一些更多的指南。

  1、SMTP协议

  熟悉并了解SMTP协议的内容,这样你可以进行更多的高级操作,甚至自己写一个满足自己特别需求的发邮件程序。以上的代码虽然简单,但是肯定还是有很多人不了解注释里提到的邮件头是什么东西,它到底对发出的邮件有什么样的影响。

  比如“发送html邮件为什么对方看到的是乱码”等等问题都可能和邮件头相关,如果对smtp协议比较了解的话,可以很快的知道问题所在。

  2、MIME规范

  如果想要发送html邮件甚至多媒体邮件,一定是需要对MIME有一定了解的,有了这方面的知识你就可以发送内容更加精彩的邮件。

  3、PEAR

  PEAR并非唯一的发送邮件的工具,但是PEAR包含了Mail、Mail_Mime等等已经封装好了的类,可以让我们的开发事半功倍,并且除了Mail方面的东西以外,它还提供了很多其他方面的现成的工具,非常值得花时间学一学。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Outlook emails lost from control panel in Windows 11 Outlook emails lost from control panel in Windows 11 Feb 29, 2024 pm 03:16 PM

Is the Outlook mail icon missing from Windows 11's Control Panel? This unexpected situation has caused confusion and concern among some individuals who rely on OutlookMail for their communication needs. Why don't my Outlook emails show up in Control Panel? There may be several possible reasons why there are no Outlook mail icons in Control Panel: Outlook is not installed correctly. Installing Office applications from the Microsoft Store does not add the Mail applet to Control Panel. The location of the mlcfg32.cpl file in Control Panel is missing. The path to the mlcfg32.cpl file in the registry is incorrect. The operating system is not currently configured to run this application

How to use mdf and mds files How to use mdf and mds files Feb 19, 2024 pm 05:36 PM

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

How to sort emails by sender, subject, date, category, size in Outlook How to sort emails by sender, subject, date, category, size in Outlook Feb 19, 2024 am 10:48 AM

Outlook offers many settings and features to help you manage your work more efficiently. One of them is the sorting option that allows you to categorize your emails according to your needs. In this tutorial, we will learn how to use Outlook's sorting feature to organize emails based on criteria such as sender, subject, date, category, or size. This will make it easier for you to process and find important information, making you more productive. Microsoft Outlook is a powerful application that makes it easy to centrally manage your email and calendar schedules. You can easily send, receive, and organize email, while built-in calendar functionality makes it easy to keep track of your upcoming events and appointments. How to be in Outloo

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

What happens when you use Hide My Email on iPhone? What happens when you use Hide My Email on iPhone? Feb 22, 2024 pm 09:19 PM

Apple offers a privacy-focused feature called "Hide Email Address" that allows users to hide their real email addresses on apps or websites that require account registration. We've taught you how to use this feature on your iPhone, now let's take a look at what's possible when using it in your daily work. What is a hidden email address on iPhone? The purpose of the Hide Email Address feature is to protect the privacy of your email address. By providing a temporary email address for application and website registration, you do not need to directly provide a person's real email address. This feature allows you to generate multiple iCloud email addresses for signing up with different services, thus avoiding revealing your true email address.

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Word mail merge prints blank page Word mail merge prints blank page Feb 19, 2024 pm 04:51 PM

If you find that blank pages appear when printing a mail merge document using Word, this article will help you. Mail merge is a convenient feature that allows you to easily create personalized documents and send them to multiple recipients. In Microsoft Word, the mail merge feature is highly regarded because it helps users save time manually copying the same content for each recipient. In order to print the mail merge document, you can go to the Mailings tab. But some Word users have reported that when trying to print a mail merge document, the printer prints a blank page or doesn't print at all. This may be due to incorrect formatting or printer settings. Try checking the document and printer settings and make sure to preview the document before printing to ensure the content is correct. if

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

See all articles