【问题标题】:Sending file from html form with Laravel-Mailgun API使用 Laravel-Mailgun API 从 html 表单发送文件
【发布时间】:2023-03-18 09:29:01
【问题描述】:

我正在尝试通过 HTML 表单发送用户选择的文件,并使用 Mailgun 将其作为电子邮件附件发送。我不想将此文件存储在我的服务器中的任何位置。我需要能够上传各种文件(png、pdf、word...)。

这是我迄今为止一直在尝试的。

前端看起来像这样:

HTML

<label>
       Click to attach file...
       <input type="file" id="file" ref="file" v-on:change="handleFileUpload" name="fileToUpload">
</label>

脚本 (VueJS)

let formData = new FormData();

formData.append('file', this.welcomeMail.attachment);


axios
.post('/admin/customersV2/sendWelcomeMail',formData,
{
    headers: {
           'Content-Type': 'multipart/form-data'
    }
})

后端(php-Laravel)看起来像这样:

$mgClient->messages()->send($domain,
    array('from'    => env('MAIL_FROM_ADDRESS'),
        'to'      => $request->emailAddress,
        'cc' => env('MAIL_CC'),
        'subject' => 'Greetings',
        'template'    => 'welcome-template',
        'attachment' => [
            [
                'filePath' => $request->file->path(),
                'fileName' => 'Attachment'
            ]
        ],
        'h:X-Mailgun-Variables'    => $mailgunVariables)

但在我的电子邮件中,附件是空的(见下面的截图):

感谢您的帮助。

【问题讨论】:

  • 你能用$request-&gt;file('file')代替$request-&gt;file-&gt;path()吗?
  • 还是不行..我有同样的临时文件附件

标签: php laravel vue.js mailgun


【解决方案1】:

这就是我最终完成的方式。问题来自后端,我必须添加 file_get_contents 才能将所有文件数据包含在一个字符串中。

    $mgClient->messages()->send($domain,
        array('from'    => env('MAIL_FROM_ADDRESS'),
            'to'      => $request->emailAddress,
            'cc' => env('MAIL_CC'),
            'subject' => 'Greetings from Eatology',
            'template'    => 'welcome-template',
            'attachment' => [
                [
                    'fileContent' => file_get_contents($request->file('file')),
                    'filename' => 'attachment.' . $request->file('file')->extension()
                ]
            ],
            'h:X-Mailgun-Variables'    => $mailgunVariables)
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2016-08-14
    • 2017-10-12
    • 2021-05-12
    • 2021-03-09
    • 2016-11-20
    • 2014-04-14
    • 2016-04-24
    相关资源
    最近更新 更多