php - Laravel 中的电子邮件附件
问题描述
我正在处理 Laravel 文件附件。我必须将 CSV 文件作为邮件附件发送,而无需将文件下载到我的服务器。当我单击提交按钮时,它没有发送带有文件附件的电子邮件。
我的控制器:
$data["email"] = $request->recipient_email;
$data["subject"] = 'Cashup Report for '. $venue->name;
$data["bodyMessage"] = $venue->name.' from '.$start.' to '.$end ;
$excel_file = Excel::create(uniqid().'Cashups', function($excel) use($transactions,$start,$end,$venue) {
$excel->sheet('New sheet', function($sheet) use($transactions,$start,$end,$venue) {
$sheet->loadView('excel.cashups', array('transactions' => $transactions, 'start'=> $start, 'end' => $end, 'venue' => $venue));
});
});
//Feedback mail to client
Mail::send('emails.cashups_report', $data, function($message) use ($data,$excel_file){
$message->from(config('mail.from.address'));
$message->to($data["email"]);
$message->subject($data["subject"]);
//Attach PDF doc
$message->attachData($excel_file,'cashups-report.xlsx');
});
我不知道我哪里出错了。我已经为此花费了很多时间,但没有找到任何解决方案。在这方面的任何指导将不胜感激。谢谢
解决方案
您可以使用下面的代码实现您的目标。我尽力在代码注释中解释所有内容。
//function to generate the csv to be attached in your email
public function createCSV()
{
$myData = MyModel::where(myConditions)->get(['col1','col2','col3']);
header('Content-Type: text/csv; charset=utf-8');
//header without attachment; this instructs the function not to download the csv
header("Content-Disposition: filename=myCsvFile.csv");
//Temporarily open a file and store it in a temp file using php's wrapper function php://temp. You can also use php://memory but I prefered temp.
$Myfile = fopen('php://temp', 'w');
//state headers / column names for the csv
$headers = array('col_name1','col_name2','col_name3');
//write the headers to the opened file
fputcsv($Myfile, $headers);
//parse data to get rows
foreach ($myData as $data) {
$row=array(
$data->col1,
$data->col2,
$data->col3,
);
//write the data to the opened file;
fputcsv($Myfile, $row);
}
//rewind is a php function that sets the pointer at begining of the file to handle the streams of data
rewind($Myfile);
//stream the data to Myfile
return stream_get_contents($Myfile);
}
第二个功能:这会将电子邮件发送给带有 csv 附件的收件人
public function sendEmail()
{
Mail::send('path_to_your_view.My_view', array(''),
function($message){
$message->to(explode(',', env('EMAILS')))
->subject('Email Subject')
->attachData($this->createCSV(), "MyfileName.csv");
});
}
/*......¯\_(ツ)_/¯......
It works on my computer*/
祝你好运!:)
推荐阅读
- javascript - 创建一个可以从其他组件调用的 Alert 组件
- javascript - 更改显示模式后的中心按钮
- unity3d - How can I make a GUI.Toggle font size and color to be bigger and in black like the example in the screenshot?
- javascript - Why CSS.registerProperty is in Javascript but not in CSS?
- powerbi - 在 Power Bi 中使用 Power Query M 的上一周日期
- sql - 将数据保存在内存中或使用数据库
- pandas - Pandas 多个“分组依据”和对值的操作
- datatables - Append Row in createRow Event
- magento - 在 magento 的自定义模块中找不到页面
- r - 在while函数中无法识别大括号?(MAC上的R)