像处理邮件txt附件一样处理php字符串

时间:2015-06-24 09:25:59

标签: php email symfony

我有一个用于生成Ical数据的php类。现在我只生成一个ical文件,但我想避免创建它,只是将我的ical数据字符串用作我可以发送的电子邮件附件。有没有办法在PHP中将字符串转换为文件而不创建它?只是将它视为一个文件?

public function sendInviteMail ($mailTutor, $mailBeneficiary, $meetingDate, $meetingEndDate, $meetingName, $meeting_location, $cancel, $UID){

    $meetingStamp = strtotime($meetingDate . " UTC");
    $meetingEndStamp = strtotime($meetingEndDate . " UTC");

    $dtstart= gmdate("Ymd\THis\Z",$meetingStamp);
    $dtend= gmdate("Ymd\THis\Z",$meetingEndStamp);
    $todaystamp = gmdate("Ymd\THis\Z");

    //Create unique identifier @todo Changer la méthode de creation récupérer l'uid en base ou le reconstruire si possible
    $cal_uid = $UID;

    $ical =    "BEGIN:VCALENDAR\n".
                "VERSION:2.0\n";
    if($cancel){
         $ical.="METHOD:CANCEL\n";
    }
    $ical .=    "BEGIN:VEVENT\n".
                "UID:".$cal_uid."\n".
                "ORGANIZER;CN=Test:".$mailTutor."\n".
                "DTSTART:".$dtstart."\n".
                "DTEND:".$dtend."\n".
                "DTSTAMP:".$todaystamp."\n".
                "DESCRIPTION:".$meetingName."\n".
                "SUMMARY:".$meetingName."\n".
                "LOCATION:".$meeting_location."\n".
                "END:VEVENT\n".
                "END:VCALENDAR";

    $ics_file = fopen('MYPATH/myicsfile.ics', "w+");
    fwrite($ics_file, $ical);
    fclose($ics_file);

    $messagetobesent = Swift_Message::newInstance('Appointment Subject')
        ->setFrom(array('admin@noreply.com' => 'John Doe'))
        ->setTo(array($mailTutor, $mailBeneficiary))
        ->setBody($message)
    ;
    $swiftAttachment = Swift_Attachment::fromPath($icsfile);
    $messagetobesent->attach($swiftAttachment);
    $this->get('mailer')->send($messagetobesent);
}

我想摆脱fopen fwrite fclose部分并附加一个只存在于内存但不存在于硬盘上的文件。

2 个答案:

答案 0 :(得分:2)

这是Swiftmailer的标准功能 - http://swiftmailer.org/docs/messages.html#attaching-dynamic-content

请参阅以下版本 - 不确定MIME类型

// Create your file contents in the normal way, but don't write them to disk
$data = 'YOUR STRING';

// Create the attachment with your data
$attachment = Swift_Attachment::newInstance($data, 'ical.ics', 'application/ics');

// Attach it to the message
$message->attach($attachment);

答案 1 :(得分:1)

如果您想使用fopen,请使用php://memory包装,而不是编写文件。

但我建议使用@edmondscommerce的解决方案