search
HomeBackend DevelopmentPHP TutorialSending Email with Attachments using PHP_PHP Tutorial

Sending Email with Attachments using PHP_PHP Tutorial

Jul 21, 2016 pm 04:12 PM
emailphpone timesendworldbringarticleuseoflookappendix

参考了一下网上的文章。俗话说,天下文章一大抄,看你会抄不会抄。关键是能为我所用,这是最重要的。废话不多讲,let‘s go。
其实发mail很简单,php有现成的函数,可以参考php 的 manual,特别是第四个例子,讲的很详细。
关键是怎么把上传附件跟邮件发送结合起来。关于文件的上传,可以参考http://blog.csdn.net/slamdunk3/archive/2005/02/23/299025.aspx 这篇文章。
讲一下 文件上传的方法及其属性:
我们假设文件上传字段的名称如上例所示,为 userfile。名称可随意命名。
表单里可以这样写:

提交之后,php利用$_FILES 数组 自动获取相关参数:
$_FILES['userfile']['name']
客户端机器文件的原名称。
$_FILES['userfile']['type']
文件的 MIME 类型,需要浏览器提供该信息的支持,例如“image/gif”。
$_FILES['userfile']['size']
已上传文件的大小,单位为字节。
$_FILES['userfile']['tmp_name']
文件被上传后在服务端储存的临时文件名。
$_FILES['userfile']['error']
和该文件上传相关的错误代码。['error'] 是在 PHP 4.2.0 版本中增加的。

注: 在 PHP 4.1.0 版本以前该数组的名称为 $HTTP_POST_FILES,它并不像 $_FILES 一样是自动全局变量。PHP 3 不支持 $HTTP_POST_FILES 数组。
当 php.ini 中的 register_globals 被设置为 on 时,您可以使用更多的变量。例如,$userfile_name 等价于 $_FILES['userfile']['name'],$userfile_type 等价于 $_FILES['userfile']['type'] 等。请记住从 PHP 4.2.0 开始,register_globals 的默认值为 off,因此我们建议您不要依赖于改设置项而使用刚刚提到的那些附加变量。
文件被上传后,默认地会被储存到服务端的默认临时目录中,除非您将 php.ini 中的 upload_tmp_dir 设置为了其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置,但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。
有了这些,我们再看与邮件相关的东西。下面是一个带附件(一个HTML文件)电子邮件的例子。

Return-Path:
Date: Mon, 22 May 2000 19:17:29 +0000
From: Someone
To: Person
Message-id:
Content-type: multipart/mixed; boundary="396d983d6b89a"
Subject: Here's the subject
--396d983d6b89a
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit

This is the body of the email.

--396d983d6b89a
Content-type: text/html; name=attachment.html
Content-disposition: inline; filename=attachment.html
Content-transfer-encoding: 8bit

 


This is the attached HTML file

 

--396d983d6b89a--


  前面的7行是邮件的头,其中值得注意的是Content-type头部分。这个头告诉邮件程序电子邮件是由一个以上的部分组成的。不含附件的邮件只有一个部分:消息本身。带附件的电子通常至少由两部分组成:消息和附件。这样,带两个附件的邮件由三部分组成:消息,第一个附件和第二个附件。

  带附件的电子邮件的不同部分之间用分界线来分隔。分界线在Content--type头中定义。邮件的每个新部分以两个连字号(--)和分界线开始。
最后一个分界线后也有两个连字号,表示这个邮件中没有其它的部分了。

  在每个分界线后有一些行,用来告诉邮件程序这个部分的内容的类型。
比如,看看上面例子中第一个分界线后面的两行--以Content-type: text/plain开头的行。这些行说明后面的部分是ISO-8859-1字符集的纯文本。跟在第二个分界线后的行告诉邮件程序现在的部分是一个HTML文件,它的名字是"attachment.html"。

  Content-disposition这持告诉邮件程序如果可能就以内嵌的方式显示附件。现在新的邮件程序会在消息后显示HTML的内容。如果Content- disposition被设为attachment,那么邮件程序就不会显示HTML文件的内容,而是显示一个连接到文件的图标(或其它的类似的东西)。收件人要看附件的内容,必须点击这个图标。一般情况下,如果附件是一些文本(包含HTML),Content-disposition会被设为inline,这是因为现在大部分邮件程序能够不借助其它浏览器而直接显示附件(文本)的内容。如果附件不是文本(比如图片或其它类似的内容),Content-disposition 就设为attachment。
我们仿照上面的例子,自己写一个php程序,可以对提交的 收信人,发送人,信件内容,附件进行处理。
首先建立一个静态页面,代码如下:



















发送者:
接受者:
下载提示:
源数据文件:
 




要注意的是 : 表单里 ENCTYPE="multipart/form-data" 一定要有。
再来看一下 发送邮件的php程序:
//文本内容
$text = $_POST['text'];
//标题
$subject = $_POST['subject'];
//发送者
$from = $_POST['from'];
//接受者
$to = $_POST['to'];
//附件
$file = $_FILES['upload_file']['tmp_name'];
// 定义分界线
$boundary = uniqid( "");
$headers = "Content-type: multipart/mixed; boundary= $boundary\r\n";
$headers .= "From:$from\r\n";
//确定上传文件的MIME类型
if($_FILES['upload_file']['type'])
$mimeType = $_FILES['upload_file']['type'];
else
$mimeType ="application/unknown";
//文件名
$fileName = $_FILES['upload_file']['name'];

// Open the file
$fp = fopen($file, "r");
// Read the entire file into a variable
$read = fread($fp, filesize($file ));
//We use the base64 method to encode it
$read = base64_encode($read);
//Cut this long string into small pieces consisting of 76 characters per line
$read = chunk_split($read);
//Now we can create the body of the email
$body = "--$boundary
Content-type: text/plain; charset=iso-8859 -1
Content-transfer-encoding: 8bit
$text
--$boundary
Content-type: $mimeType; name=$fileName
Content-disposition: attachment; filename=$ fileName
Content-transfer-encoding: base64
$read
--$boundary--";
//Send mail
if(mail($to, $subject,$body, $headers))
print "OK! the mail $from --- $to has been send
";
else
print "fail to send mail
";
?>
It doesn’t matter if you don’t understand, let me explain:
1. The structure of the email header: generally includes
Content-type. To send attachments, set it to multipart/mixed, which means multiple parts (email itself + attachments).
boundary is the dividing line mentioned above. Its value is obtained using the uniqid(); function that comes with PHP.
Receiver, CC, etc., followed by From: Cc:. Use rn to separate it from the Content-type boundary above.
2 Email body
If it is plain text email content, its format is as follows:
Content-type: text/plain; charset=iso-8859-1
Content-transfer-encoding: 8bit
Add the text content of the email immediately after.
If it is an attachment:
Content-type: $mimeType; name=$fileName
Content-disposition: attachment; filename=$fileName
Content-transfer-encoding: base64
followed by Then add the attachment content.
$mimeType is the MIME type of the attachment. Can be obtained using $_FILES['upload_file']['type'].
$fileName is the name of the attachment
The email text content and attachment are separated by boundary.
Some people may ask, what is the content of the attachment? The content of the attachment is to use the read function to read the uploaded attachment, and then base64 encode it and then use chunk_split to split it into N chunks. The size of each chunk is the default 76 characters.
Okay, let’s look at that program now. There should be no problem, right? Just bring the corresponding variables into the mail function.
The above program was tested under PHP Version 4.3.8 freeBSD.
Reference article: "php sends email with attachments Author: cn-linux"

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313784.htmlTechArticleReference articles on the Internet. As the saying goes, if you copy a lot of articles in the world, it depends on whether you can copy them or not. The key is to be able to use it for me, that's the most important thing. Without further ado, let’s go. Actually...
Statement
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),