我正在尝试将附件添加到我起草但似乎无法正常工作的电子邮件中。我尝试按照此处和此处的示例进行操作,但没有成功。
到目前为止,这是我能做的:
- 连接到 Exchange 服务器
- 打开邮箱
- 起草 html 电子邮件
- 将电子邮件附加到邮箱并让它正确呈现 html。(当使用 text/html 作为内容类型时)。使用其他任何内容都会将 html 显示为纯文本。
作为附加说明,在起草后,电子邮件会附加到 Exchange 2010 服务器上的邮箱中,然后通过 Outlook 2010 进行查看然后发送。
下面是我的邮件类和起草电子邮件的代码。
邮件程序.php
<?php
class mailer
{
const USER = 'user';
const PASSWORD = 'pass';
const MAILBOX = '{conn}DRAFTS';
// STRING ORDER: $content-type . $from . $to . $cc . $subject . "\r\n\r\n" . $message
public $message;
public $imap_conn;
public $boundary;
function __construct()
{
// Open the message property so we can start appending strings.
$this->message = '';
// Open the IMAP connection
$this->imap_conn = imap_open(self::MAILBOX,self::USER,self::PASSWORD);
}
public function content_type($string_type)
{
$this->message .= "Content-type:{$string_type}\r\n";
}
public function from($string_from)
{
$this->message .= "From:{$string_from}\r\n";
}
public function to($string_to)
{
$this->message .= "To:{$string_to}\r\n";
}
public function cc($string_cc)
{
$this->message .= "Cc:{$string_cc}\r\n";
}
public function mime($float_mime_version)
{
$this->message .= "MIME-Version:{$float_mime_version}\r\n";
}
public function subject($string_subject)
{
$this->message .= "Subject:{$string_subject}\r\n\r\n";
}
public function message($string_message)
{
$this->message .= "{$string_message}\r\n";
}
public function set_boundary($string_boundary)
{
$this->boundary = $string_boundary;
}
public function append()
{
imap_append($this->imap_conn,self::MAILBOX,$this->message,"\\Draft");
imap_close($this->imap_conn);
}
}
?>
代码草案
// A random hash used for the boundary
$rh = md5(date('c',time()));
$data = chunk_split(base64_encode('Testing'));
$m = new mailer;
$m->set_boundary('--PHP-mixed-' . $rh);
$m->content_type('multipart/mixed; boundary="' . $m->boundary . '"');
$m->mime('1.0');
$m->from('from@mail.com');
$m->to('to@mail.com');
$m->cc('cc1@mail.com,cc2@mail.com');
$m->subject('A new email');
$m->message("
{$m->boundary}
Content-Type: text/html; charset=\"utf-8\"
Content-Transfer-Encoding: base64
Testing my <b>HTML</b>
</br>
{$m->boundary}
Content-Type: application/octet-stream; name=\"test.txt\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"test.txt\"
{$data}
{$m->boundary}--
"));
$m->append();
附加前的消息
Content-type:multipart/mixed; boundary="--PHP-mixed-b408f941593cf92b5a8bd365abb4e64f"
MIME-Version:1.0
From:from@mail.com
To:to@mail.com
Cc:cc1@mail.com
Subject:New Message
--PHP-mixed-b408f941593cf92b5a8bd365abb4e64f
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: "base64"
My <b>html</b> content
--PHP-mixed-b408f941593cf92b5a8bd365abb4e64f
Content-Type: application/octet-stream; name="test.txt"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="test.txt"
--PHP-mixed-b408f941593cf92b5a8bd365abb4e64f--