[英]How do you send a templated Mailgun email with Laravel?
我試圖弄清楚是否有辦法通過 Laravel 可郵寄的方式發送 Mailgun 模板。
以下代碼使用刀片視圖發送我的 email 罰款:
return $this->from(['address'=>'no-reply@domain.com', 'name'=>'Domain'])
->subject("subject")
->replyTo(['address'=>'sales@domain.com'])
->view('emails.deliverReport')
->withSwiftMessage(function($message){
$headers = $message->getHeaders();
$headers->addTextHeader("X-Mailgun-Variables", '{"type": "asset-delivery"}');
$headers->addTextHeader("X-Mailgun-Tag", "asset-delivery");
});
我想發送一個我在 Mailgun 上創建的模板,而不是使用刀片模板。
您可以通過將模板作為表單數據發送來使用 CURL 執行此操作:
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
-F from='Sender Bob <sbob@YOUR_DOMAIN_NAME>' \
-F to='alice@example.com' \
-F subject='Hello' \
-F template='template.test' \
-F h:X-Mailgun-Variables='{"title": "API documentation", "body": "Sending messages with templates"}'
有沒有人通過 Laravel 可郵寄的方式發送 Mailgun 模板?
很可能這不再與您有關,但它回答了問題。 我創建了一個 庫,該庫添加了一個新的通知通道以將模板化消息發送到 Laravel; 這分解為以下內容:
創建一個新頻道:
class MailgunTemplatesChannel { public function __construct(private Mailgun $mailgun) public function send($notifiable, Notification $notification): void { [$template, $params] = $notification->toMailgun($notifiable); // Route the notification to the mail recipient address $params['to'] = $notifiable->routeNotificationFor('mail'); $this->mailgun->messages()->send([ 'template' => $template, ...$params, ]); } }
設置 Mailgun 並在服務提供商中注冊頻道:
class AppServiceProvider extends ServiceProvider public function register(): void { //... // Configure Mailgun $this->app->bind(Mailgun::class, fn() => Mailgun::create( config('services.mailgun.secret'), config('services.mailgun.endpoint', 'https://api.mailgun.net'), )); // Register the channel Notification::resolved(fn(ChannelManager $service) => $service->extend( 'mailgun', // This is the notification channel identifier fn(Application $app) => $app->make(MailgunTemplatesChannel::class) )); }
配置通知以通過新的 Mailgun 通道發送:
class MyTestNotification extends Notification { public function toMailgun(): array { return [ 'subject' => 'Your subject', 'template' => 'name_of_the_template', 'v:some_variable' => 'a template variable value', ]; } public function via(): array { return [ 'mailgun' ]; } }
通過 Mailgun 發送通知:
$user->notify(new MyTestNotification());
請不要只是將其復制粘貼到您的應用程序中! 這是如何為模板化消息構建自定義通道的粗略概述,但它還有很多不足之處。
如果您想要生產就緒的 package,請查看matchory/laravel-mailgun-templates-channel 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.