//加載PHP IMAP擴(kuò)展
extension_loaded('imap');
//連接到您的電子郵件服務(wù)器
$hostname = '{imap.example.com:993/imap/ssl}INBOX';
$username = 'username';
$password = 'password';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());
//獲取第一封郵件
$emails = imap_search($inbox,'ALL');
if($emails){
$email_number = $emails[0];
$header = imap_headerinfo($inbox,$email_number);
//檢查是否有附件
if($header->ifdisposition){
$attachments = imap_fetchstructure($inbox, $email_number);
if($attachments->parts){
foreach($attachments->parts as $part){
//檢查類型為文本并且有文件名的部件
if($part->subtype == 'PLAIN' && $part->ifdparameters && $part->dparameters[0]->attribute == 'FILENAME'){
$attachment_name = $part->dparameters[0]->value;
$attachment_data = imap_fetchbody($inbox,$email_number,$part->partnumber);
$attachment_data = base64_decode($attachment_data);
//處理附件內(nèi)容
echo $attachment_data;
}
}
}
}
}
//獲取文件內(nèi)容和文件名
$file_name = $_FILES['attachment']['name'];
$file_contents = file_get_contents($_FILES['attachment']['tmp_name']);
//將附件添加到電子郵件
//連接到您的電子郵件服務(wù)器
$hostname = '{imap.example.com:993/imap/ssl}INBOX';
$username = 'username';
$password = 'password';
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mailbox: ' . imap_last_error());
//創(chuàng)建一個(gè)新郵件
imap_mail_compose(array(
'to' =>'example@example.com',
'subject' =>'Test email with attachment',
'attachments' =>array(
array(
'name' =>$file_name,
'content' =>$file_contents,
'type' =>mime_content_type($file_name)
)
),
));
//發(fā)送郵件
imap_send($inbox, $email);