Swift Mailer附件

4

我使用PHP动态创建了CSV文件,现在需要将此CSV文件附加到Swift Mailer消息中。我已尝试使用file_get_content获取所创建文件的内容,也尝试使用chunk_split(base64_encode(file_get_contents()))对所创建文件进行编码,并在将文件写入磁盘之前对其进行附加。如果不写入磁盘,则在CSV中得到资源#183,如果使用file_get_content附加,则在CSV文件的每一行中只有一个字符串。请问我做错了什么?

if(!file_exists(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv'))
 {
  if($file = fopen (_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'x+'))
   {
   foreach ($list as $fields)
    {
     fputcsv($file, $fields);
    }



    $attachment['mime'] = 'application/vnd.ms-excel';
    $attachment['content'] = file_get_contents($file);
    $attachment['name'] = $order.'order';
  EDIT            
 Mail::Send(1, 'order_conf', 'Order CSV Attachment', $success, 'test@email.com', Address, NULL, NULL, $attachment); // attach and send
      }
      }

你能展示一下你用来附加附件的代码吗? - Pekka
“CSV文件中每行的字符串”是什么意思? - Pekka
我可以成功创建文件,但是在发送文件时遇到了问题。我的意思是,数组中的每个项目应该被分配到行中的单独单元格中,但实际上第一行(例如A1)将包含由逗号分隔的数组中所有值。 - Dan
你可能想要使用fclose关闭$file并将其unset...而且只需使用file_get_contents(PS_ORDERS_DIR.$orderDate.'/'.$file_name.'.csv')代替file_get_contents($file);? - Gekkie
2个回答

7

将文件附加到Swift Mailer中:

$swift =& new Swift(new Swift_Connection_SMTP(MAIL_SMTP_URL, MAIL_SMTP_PORT));
$message =& new Swift_Message($subject);
$recpients =& new Swift_RecipientList();
$sender =& new Swift_Address('info@example.com', 'example.com');
$recpients->addTo('info@example.com', 'www.example.com');

$message->attach(new Swift_Message_Part('this is my body'));
$message->attach(new Swift_Message_Attachment($binarycontents, $fileTitle, $mimeType));
$swift->send($message, $recpients, $sender);

在您的情况下,附加将是:

$message->attach(new Swift_Message_Attachment(file_get_contents($file), $order.'order.csv', 'application/vnd.ms-excel'));

仅作为示例,当然 :)


0
//to set headers of csv file(first row)
$content = "user_id,first_name,last_name,phone,gender,pan_number\r\n";

//this can be dynamic data from database or from anywhere can loop this for multiple rows
$content .= "1,test_fn,test_ln,8888999900,M,ASDD3333\r\n";

//include swiftmailer library in order to run the below code
Yii::$app->mailer->compose()
->setFrom(array('test@test.com'=>'test'))
->setTo('testto@testto.com')
->setSubject('your subject' )
->setHtmlBody('<table><tr><td>your email body message here</td></tr>       </table>')
->attachContent($content, ['fileName' => 'user.csv', 'contentType' => 'application/vnd.ms-excel'])->send();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接