Git Product home page Git Product logo

mailersend-laravel-driver's Introduction

MailerSend Laravel Driver

MIT licensed

Table of Contents

Installation

Requirements

For Laravel 7.x - 8.x support see 1.x branch

Setup

You can install the package via composer:

composer require mailersend/laravel-driver

After that, you need to set MAILERSEND_API_KEY in your .env file:

MAILERSEND_API_KEY=

Add MailerSend as a Laravel Mailer in config/mail.php in mailers array:

'mailersend' => [
    'transport' => 'mailersend',
],

And set environment variable MAIL_MAILER in your .env file

MAIL_MAILER=mailersend

Also, double check that your FROM data is filled in .env:

MAIL_FROM_ADDRESS=[email protected]
MAIL_FROM_NAME="App Name"

Usage

Old Syntax:

This is an example using the build mailable that you can use to send an email with.

app/Mail/TestEmail.php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use MailerSend\Helpers\Builder\Variable;
use MailerSend\Helpers\Builder\Personalization;
use MailerSend\LaravelDriver\MailerSendTrait;

class TestEmail extends Mailable
{
    use Queueable, SerializesModels, MailerSendTrait;

    public function build()
    {
        // Recipient for use with variables and/or personalization
        $to = Arr::get($this->to, '0.address');

        return $this
            ->view('emails.test_html')
            ->text('emails.test_text')
            ->attachFromStorageDisk('public', 'example.png')
            // Additional options for MailerSend API features
            ->mailersend(
                template_id: null,
                variables: [
                    new Variable($to, ['name' => 'Your Name'])
                ],
                tags: ['tag'],
                personalization: [
                    new Personalization($to, [
                        'var' => 'variable',
                        'number' => 123,
                        'object' => [
                            'key' => 'object-value'
                        ],
                        'objectCollection' => [
                            [
                                'name' => 'John'
                            ],
                            [
                                'name' => 'Patrick'
                            ]
                        ],
                    ])
                ],
                precedenceBulkHeader: true,
                sendAt: new Carbon('2022-01-28 11:53:20'),
            );
    }
}

New Syntax:

This is an example using the new mailable syntax that you can use to send an email with.

app/Mail/TestEmail.php

<?php

namespace App\Mail;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use MailerSend\Helpers\Builder\Personalization;
use MailerSend\Helpers\Builder\Variable;
use MailerSend\LaravelDriver\MailerSendTrait;

class TestEmail extends Mailable
{
    use Queueable, SerializesModels, MailerSendTrait;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Test Email',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        $to = Arr::get($this->to, '0.address');

        // Additional options for MailerSend API features
        $this->mailersend(
            template_id: null,
            variables: [
                new Variable($to, ['name' => 'Your Name'])
            ],
            tags: ['tag'],
            personalization: [
                new Personalization($to, [
                    'var' => 'variable',
                    'number' => 123,
                    'object' => [
                        'key' => 'object-value'
                    ],
                    'objectCollection' => [
                        [
                            'name' => 'John'
                        ],
                        [
                            'name' => 'Patrick'
                        ]
                    ],
                ])
            ],
            precedenceBulkHeader: true,
            sendAt: new Carbon('2022-01-28 11:53:20'),
        );

        return new Content(
            view: 'emails.test_html',
            text: 'emails.test_text'
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [
            Attachment::fromStorageDisk('public', 'example.png')
        ];
    }
}

We provide a MailerSendTrait trait that adds a mailersend method to the mailable and allows you to use additional options that are available through our API.

After creating the mailable, you can send it using:

use App\Mail\TestEmail;
use Illuminate\Support\Facades\Mail;

Mail::to('[email protected]')
    ->cc('[email protected]')
    ->bcc('[email protected]')
    ->send(new TestEmail());

Please refer to Laravel Mail documenation and MailerSend API documentation for more information.

Support and Feedback

In case you find any bugs, submit an issue directly here in GitHub.

If you have any troubles using our driver, feel free to contact our support by email [email protected]

Official API documentation is at https://developers.mailersend.com

License

The MIT License (MIT)

mailersend-laravel-driver's People

Contributors

aaronpk avatar dinomh avatar doobas avatar fosron avatar gausejakub avatar jestherthejoker avatar joaofscruz avatar mariovalney avatar nklmilojevic avatar peterocansey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mailersend-laravel-driver's Issues

Unexpected EOF for \"https://api.mailersend.com/v1/email\" symfony/http-client/Response/CurlResponse.php:338

Hello Team,

I am getting following error while trying to send mail using jobs.

Unexpected EOF for "https://api.mailersend.com/v1/email\". at /var/www/html/public/vendor/symfony/http-client/Response/CurlResponse.php:338

Here is my code structure:

class SendMailTemplate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected string $email;
    protected string $template;
    protected string $subject;
    protected array $values;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email, $subject, $template, $values = [])
    {
        $this->email = $email;
        $this->subject = $subject;
        $this->template = $template;
        $this->values = $values;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        Mail::to($this->email)->send(new MailerSendMail($this->template, $this->subject, $this->values));
    }
class MailerSendMail extends Mailable
{
    use Queueable, SerializesModels, MailerSendTrait;

    private array $templates = [
        ...
    ];

    public $subject;
    public array $values;
    protected mixed $template_id;
    public ?Carbon $timestamp;


    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(string $templateName, string $subject, array $values, Carbon $timestamp = null)
    {
        $this->template_id = $this->templates[$templateName];
        $this->values = $values;
        $this->subject = $subject;
        $this->timestamp = $timestamp ?? null;
    }

    /**
     * Build the message.
     *
     * @return $this
     * @throws MailerSendAssertException
     */
    public function build(): static
    {
        $to = Arr::get($this->to, '0.address');

        return $this->subject($this->subject)->mailersend(
            template_id: $this->template_id,
            personalization: [
                new Personalization($to, $this->values)
            ],
            sendAt: $this->timestamp
        );

    }
}
....
       SendMailTemplate::dispatch($session->user->email, "Charging Ended", "chargingEnded", $variables);
....

Issues with email attachments

Context: Laravel 10 / PHP 8.2

We've encountered an issue in sending an email with a raw data (JSON) attachment. We use multiple mailers and this issue is only encountered using mailersend, mailgun works as intended. I'm not sure where this inconsistency comes from, and due to the fact that mailgun works where mailersend doesn't it seems as if it's an issue.

We use a json-encoded PHP array to send a .json file to the email recipient.

This is the code we're using currently (with identifiable information replaced):

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;


class MyMail extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;
    
    public $data;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = json_encode($data);
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $subject = 'My Email';
        $name = 'Me';
        $from = '[email protected]';

        return $this->from($from, $name)
                    ->subject($subject)
                    ->view('myEmailTemplate')
                    ->attachData($this->data, 'myJsonData.json', [
                        'mime' => 'application/json',]);               
    }
}

I have also attempted using the new laravel attachments method like this:

public function attachments(): array
  {
      return [
          Attachment::fromData(fn () => $jsonData, 'myJsonData.json')
              ->withMime('application/json'),
      ];
  }

Both attempts result in this message returned by the mailersend API:
Could not validate the attached file. Filename and attached file does not match. #MS42202

No way of using Advanced personalization with this package

I'm trying to use a foreach loop in my template with the advanced personalization but I can only set simple substitutions variables using the Variable builder class.

Is it currently possible to use advanced personalization using this package? I can't seem to find any documentation, except the developer api docs for the general API.

Api docs here.

Using mailersend driver in laravel with a Mailable, errors out with message, One of template_id or text must be supplied

I am using mailersend driver in my laravel application. I have installed mailersend/laravel-driver successfully.
Configured my .env variables,
MAIL_MAILER=mailersend
MAILERSEND_API_KEY=xxxxx
MAIL_FROM_ADDRESS="no-reply@xxxx" MAIL_FROM_NAME="${APP_NAME}"

My mailable class:

`class ClientAccountCredentials extends Mailable
{
use Queueable, SerializesModels;

public function __construct(
    public Client $client,
)
{
}

public function envelope(): Envelope
{
    return new Envelope(
        to: [$this->client->email],
        subject: "Your {$this->client->company->name} Account Credentials"
    );
}

public function content(): Content
{
    return new Content(
        view: 'emails.client-account-credentials',
    );
}

public function attachments(): array
{
    return [];
}

}`

How it's initiated:
Mail::to( users: $client )->send( mailable: new ClientAccountCredentials( client: $client, ) );

The error
One of template_id or text must be supplied {"userId":1,"exception":"[object] (MailerSend\\Exceptions\\MailerSendAssertException(code: 0): One of template_id or text must be supplied at /var/www/html/project/public_html/vendor/mailersend/mailersend/src/Helpers/GeneralHelpers.php:23)

Add support for failover

Laravel provides failover configuration for the mail drivers.
That means, in case the mail driver doesn't work, it would retry with the next registered driver to send emails.
Doc: https://laravel.com/docs/10.x/mail#failover-configuration

Currently, it doesn't work with mailersend.
The reason it doesn't work is because Symfony's Mail Transport catches exceptions through TransportExceptionInterface.
However, when something goes wrong, MailerSend throws MailerSendException.
Ref: https://github.com/symfony/mailer/blob/7.0/Transport/RoundRobinTransport.php#L56-L60

And because of that, it doesn't find the exception and can not retry with another fallback driver.

Now to make this work, we need to throw TransportException instead of MailerSendException.

Incompatibilities with other packages

When trying to install this I found that it was incompatible with:

sentry/sentry-laravel
mailerlite/mailerlite-api-v2-php-sdk

Most of the issues cam from the guzzle6-adapter dependencies which requires packages such as php-http/httplug and php-http/discovery. Those underlying packages have conflicts with the versions the other packages use

Using mailersend templates

Hi,

Im trying out the package with a simple Laravel mailable and referencing a template as per the documentation as follows:

`
class UserCreated extends Mailable
{
use Queueable, SerializesModels, MailerSendTrait;

    public function build()
    { 
        $variables = [
            new Variable('[email protected]', [
                'name' => 'Joe'
                'company' => 'Acme Co'
            ])
        ];
    
        return $this
            ->mailersend('ynrw7gy2pn42k8e3', $variables);
    }
}

`

However, this expects a blade view (see error attached).
If we adding a blade view with ->view('emails.test_html') then ends up sending the mail but ignoring the template.
Am I doing this correctly - or does the template ID need to be passed in a different way?

image
image

Error in MailersendTrait with new sendAt

The new implemented sendAt for mailersend method of MailerSendTrait produces errors or at least PHP warnings, if no date is set. trying to access property timestamp of null.

Arr::set($mailersendData, MailerSendTransport::MAILERSEND_DATA_SEND_AT, $sendAt->timestamp);

Perhaps replace with:

if(isset($sendAt)) {
    Arr::set($mailersendData, MailerSendTransport::MAILERSEND_DATA_SEND_AT, $sendAt->timestamp); 
}

Compatibility issues with Laravel 10.X.

My composer.json:
"require": {
"php": "^8.2",
"devnoiseconsulting/laravel-scout-postgres-tsvector": "^9.1",
"doctrine/dbal": "^3.6.1",
"guzzlehttp/guzzle": "^7.7",
"http-interop/http-factory-guzzle": "^1.2",
"inertiajs/inertia-laravel": "^0.6.9",
"laravel/framework": "^v10.5.1",
"laravel/horizon": "^5.16",
"laravel/pennant": "^1.2",
"laravel/sanctum": "^v3.2.1",
"laravel/scout": "^10.0",
"laravel/socialite": "^5.6",
"laravel/tinker": "^2.7",
"laravel/vapor-cli": "^1.58",
"laravel/vapor-core": "^2.31",
"laravel/vapor-ui": "^1.7",
"league/flysystem-aws-s3-v3": "^3.0",
"meilisearch/meilisearch-php": "^1.0",
"predis/predis": "^2.1",
"propaganistas/laravel-phone": "^5.0",
"pusher/pusher-php-server": "^7.2",
"spatie/laravel-cookie-consent": "^3.2",
"spatie/laravel-data": "^3.2",
"spatie/laravel-event-sourcing": "^7.3",
"spatie/laravel-medialibrary": "^10.7",
"spatie/laravel-model-states": "^2.4",
"spatie/laravel-settings": "^2.8.3",
"spatie/laravel-sitemap": "^6.3",
"spatie/laravel-typescript-transformer": "^2.1.7",
"spatie/typescript-transformer": "^2.1",
"stancl/tenancy": "^3.7",
"staudenmeir/laravel-adjacency-list": "^1.0",
"stripe/stripe-php": "^10.21",
"tightenco/ziggy": "^1.5"
},

Output:

Problem 1
- mailersend/laravel-driver v2.2.0 requires mailersend/mailersend ^0.8.0 -> satisfiable by mailersend/mailersend[v0.8.0].
- mailersend/laravel-driver[v0.1.0, ..., v0.1.1] require php ^7.4 -> your php version (8.2; overridden via config.platform, actual: 8.2.7) does not satisfy that requirement.
- mailersend/laravel-driver[v1.0, ..., v1.1.1] require illuminate/support ^7.0|^8.0 -> found illuminate/support[v7.0.0, ..., v7.30.6, v8.0.0, ..., v8.83.27] but these were not loaded, likely because it conflicts with another require.
- mailersend/laravel-driver[v2.0.0, ..., v2.1.0] require illuminate/support ^9.0 -> found illuminate/support[v9.0.0, ..., v9.52.15] but these were not loaded, likely because it conflicts with another require.
- mailersend/mailersend v0.8.0 requires psr/http-message ^1.0 -> found psr/http-message[1.0, 1.0.1, 1.1] but the package is fixed to 2.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
- Root composer.json requires mailersend/laravel-driver * -> satisfiable by mailersend/laravel-driver[v0.1.0, v0.1.1, v1.0, ..., v1.1.1, v2.0.0, v2.1.0, v2.2.0].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require mailersend/laravel-driver:*" to figure out if any version is installable, or "composer require mailersend/laravel-driver:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

PSR/HTTP-MESSAGE 2.0 work?

Can we update composer.json to support psr/http-message 2.0 yet?

Problem 1
- mailersend/mailersend v0.8.0 requires psr/http-message ^1.0 -> found psr/http-message[1.0, 1.0.1, 1.1] but the package is fixed to 2.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Usage with Laravel 10

Following your official tutorial in the dashboard:

php artisan make:mail ExampleEmail

creates this :

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class ExampleEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Hello Steve',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: "mail.example"
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

That means there is no build method anymore so how to do this example of your official tutorial in Laravel 10?

public function build()
    {
        $to = Arr::get($this->to, '0.address');

        return $this->view('emails.test_html')
            ->text('emails.test_text')
            ->attachFromStorageDisk('public', 'example.png')
            ->mailersend(
                // Template ID
                null,
                // Variables for simple personalization
                [
                    new Variable($to, ['name' => 'Your Name'])
                ],
                // Tags
                ['tag'],
                // Advanced personalization
                [
                    new Personalization($to, [
                        'var' => 'variable',
                        'number' => 123,
                        'object' => [
                            'key' => 'object-value'
                        ],
                        'objectCollection' => [
                            [
                                'name' => 'John'
                            ],
                            [
                                'name' => 'Patrick'
                            ]
                        ],
                    ])
                ]
        );
    }

Laravel 10 install issue, psr/http-message mismatch

Laravel 10 requires psr/http-message 2.0. but mailersend/laravel-driver requires 1.0. Downgrading the laravel requirement solves this, but seems to me not a great idea. Tested on older migrated L9 to L10 app, but also on fresh Laravel 10 install, and issue persisted. Please update mailersend/laravel-driver. TNX!

mailersend/mailersend v0.8.0 requires psr/http-message ^1.0 -> found psr/http-message[1.0, 1.0.1, 1.1] but the package is fixed to 2.0

I got error "One of template_id or text must be supplied"

I'm using Laravel 10, and I think this repo has bug.

This is my mail class

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use MailerSend\LaravelDriver\MailerSendTrait;

class SubscriberConfirmationEmail extends Mailable
{
    use Queueable,
        SerializesModels,
        MailerSendTrait;
    
    public function __construct(public $subscriber)
    {
    }
    
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Confirm your email',
        );
    }
    
    public function content(): Content
    {
        $confirmationLink = route('subscribe.confirm', ['token' => $this->subscriber->confirmation_token]);
        
        return new Content(
            view: 'emails.subscribers.confirmation',
            with: [
                'firstName' => $this->subscriber->first_name,
                'confirmationLink' => $confirmationLink,
            ]
        );
    }
    
    public function attachments(): array
    {
        return [];
    }
}

When I submitted it and got the error MailerSend\Exceptions\MailerSendAssertException One of template_id or text must be supplied
I don't use any template and just want to use view template (Laravel Blade)
I tested sending it to Mailtrap and it success.

Can anyone help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.