GithubHelp home page GithubHelp logo

mailgun's Introduction

Bogardo/Mailgun

A package for the Laravel Framework for sending emails using the Mailgun API. The syntax for sending emails is very similar to the Laravel Mail component.

Laravel already supports sending emails via the Mailgun API out of the box but it doesn't support Mailgun specific features.

This packages fills that gap and supports most of the mail features offered by Mailgun:

  • Open & Click tracking
  • Campaigns
  • Tags
  • Scheduled delivery
  • Batch sending
  • Custom data/headers

This package makes use of the mailgun-php library.

Total Downloads Monthly Downloads License Gitter

Basic Example
Mailgun::send('emails.invoice', $data, function ($message) {
    $message
        ->subject('Your Invoice')
        ->to('[email protected]', 'John Doe')
        ->bcc('[email protected]')
        ->attach(storage_path('invoices/12345.pdf'))
        ->trackClicks(true)
        ->trackOpens(true)
        ->tag(['tag1', 'tag2'])
        ->campaign(2);
});

Version Compatibility

This package currently supports Laravel 5.1 and up. For older versions of Laravel please refer to older versions of this package.

Installation

Install the package via composer

composer require bogardo/mailgun

If using Laravel 5.1 to 5.4, Register the ServiceProvider and (optionally) the Facade

// config/app.php

'providers' => [
    ...
    Bogardo\Mailgun\MailgunServiceProvider::class

];

...

'aliases' => [
	...
    'Mailgun' => Bogardo\Mailgun\Facades\Mailgun::class
],

Next, publish the config file with the following artisan command.

php artisan vendor:publish --provider="Bogardo\Mailgun\MailgunServiceProvider" --tag="config"

or if using Laravel 5.5

php artisan vendor:publish

After publishing, add and fill the next values to your .env file

# Domain name registered with Mailgun
MAILGUN_DOMAIN=

# Mailgun (private) API key
MAILGUN_PRIVATE=

# Mailgun public API key
MAILGUN_PUBLIC=

# You may wish for all e-mails sent with Mailgun to be sent from
# the same address. Here, you may specify a name and address that is
# used globally for all e-mails that are sent by this application through Mailgun.
MAILGUN_FROM_ADDRESS=
MAILGUN_FROM_NAME=

# Global reply-to e-mail address
MAILGUN_REPLY_TO=

# Force the from address
#
# When your `from` e-mail address is not from the domain specified some
# e-mail clients (Outlook) tend to display the from address incorrectly
# By enabling this setting, Mailgun will force the `from` address so the
# from address will be displayed correctly in all e-mail clients.
#
# WARNING:
# This parameter is not documented in the Mailgun documentation
# because if enabled, Mailgun is not able to handle soft bounces
MAILGUN_FORCE_FROM_ADDRESS=

# Testing
# 
# Catch All address
#
# Specify an email address that receives all emails send with Mailgun
# This email address will overwrite all email addresses within messages
MAILGUN_CATCH_ALL=

# Testing
# 
# Mailgun's testmode
#
# Send messages in test mode by setting this setting to true.
# When you do this, Mailgun will accept the message but will
# not send it. This is useful for testing purposes.
#
# Note: Mailgun DOES charge your account for messages sent in test mode.
MAILGUN_TESTMODE=

You can also configure the package in your config/mailgun.php.

HTTP Client Dependency

To remove the dependency for a specific HTTP client library (e.g. Guzzle) the mailgun-php library has a dependency on the virtual package php-http/client-implementation which allows you to install any supported client adapter, it does not care which one. Please refer to the documentation for more information.

This gives you the freedom to use any (supported) client for communicating with the Mailgun API. To register your driver you must register it in the Service Container with the mailgun.client key.

The registration must occur before the MailgunServiceProvider is being registered.

Guzzle 6 example implementation

Install the dependencies:

$ composer require php-http/guzzle6-adapter

Add the following to your AppServiceProvider register() method.

$this->app->bind('mailgun.client', function() {
	return \Http\Adapter\Guzzle6\Client::createWithConfig([
		// your Guzzle6 configuration
	]);
});



Usage

The Mailgun package offers most of the functionality as the Laravel Mail component.

The Mailgun::send() method may be used to send an e-mail message:

Mailgun::send('emails.welcome', $data, function ($message) {
    $message->to('[email protected]', 'John Doe')->subject('Welcome!');
});

Views

The first argument passed to the send method is the name of the view that should be used as the e-mail body. Mailgun supports 2 types of bodies: text and html. You can specify the type of body like so:

Mailgun::send(['html' => 'emails.htmlmail', 'text' => 'emails.textmail'], $data, $callback);

If you have an html body as well as a text body then you don't need to specify the type, you can just pass an array where the first item is the html view and the second item the text view.

Mailgun::send(['emails.htmlmail','emails.textmail'], $data, $callback);

When you only want to send an html body you can just pass a string.

Mailgun::send(['emails.htmlmail'], $data, $callback);

When only sending a text body, just must pass an array and specify the type.

Mailgun::send(['text' => 'emails.textmail'], $data, $callback);

Raw

If you do not want to use a template you can use the raw() method.

Mailgun::raw("This is the email body", $callback);

Data

The second argument passed to the send method is the $data array that is passed to the view.

Note: A $message variable is always passed to e-mail views, and allows the inline embedding of attachments. So, it is best to avoid passing a (custom) message variable in your view payload.

You can access the values from the $data array as variables using the array key.

Example:

$data = [
	'customer' => 'John Doe',
	'url' => 'http://laravel.com'
];

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->to('[email protected]', 'John Doe')->subject('Welcome!');
});

View emails.welcome:

<body>
    Hi {{ $customer }},
	Please visit {{ $url }}
</body>

Which renders:

<body>
    Hi John Doe,
	Please visit http://laravel.com
</body>

Mail options

You can specify the mail options within the closure.

Recipients

The to method

Mailgun::send('emails.welcome', $data, function($message) {
	$message->to('[email protected]', 'Recipient Name');
});

The cc method

$message->cc('[email protected]', 'Recipient Name');

The bcc method

$message->bcc('[email protected]', 'Recipient Name');

Batch Sending

Mailgun supports the ability send to a group of recipients through a single API call. This is achieved by specifying multiple recipient email addresses as to parameters and using Recipient Variables.

Recipient Variables are custom variables that you define, which you can then reference in the message body. They give you the ability to send a custom message to each recipient while still using a single API Call.

To access a recipient variable within your email, simply reference %recipient.yourkey%.

Warning: It is important when using Batch Sending to also use Recipient Variables. This tells Mailgun to send each recipient an individual email with only their email in the to field. If they are not used, all recipients’ email addresses will show up in the to field for each recipient.

Examples
use Bogardo\Mailgun\Mail\Message;

Mailgun::send('email.batch', $data, function(Message $message){
    $message->to([
        '[email protected]' => [
            'name' => 'User One',
            'age' => 37,
            'city' => 'New York'
        ],
        '[email protected]' => [
            'name' => 'User Two',
            'age' => 41,
            'city' => 'London'
        ]
    ]);
});

// Or

Mailgun::send('email.batch', $data, function(Message $message){
    $message->to('[email protected]', 'User One', [
        'age' => 37, 
        'city' => 'New York'
    ]);
    $message->to('[email protected]', 'User Two', [
        'age' => 41,
        'city' => 'London'
    ]);
});
// resources/views/email/batch.blade.php

Hi %recipient.name%,

Age: %recipient.age%
City: %recipient.city%

Note: Mailgun limits the number of recipients per message to 1000

Sender

In the Mailgun config file you have specified the from address. If you would like, you can override this using the from method. It accepts two arguments: email and name where the name field is optional.

// with name
$message->from('[email protected]', 'Recipient Name');

// without name
$message->from('[email protected]');
Subject

Setting the email subject

$message->subject('Email subject');
Reply-to

Setting a reply-to address

$message->replyTo('[email protected]', 'Helpdesk');

If the reply_to config setting is set, the reply-to will be automatically set for all messages You can overwrite this value by adding it to the message as displayed in the example.

Attachments

To add an attachment to the email you can use the attach method. You can add multiple attachments.

The attach method accepts 2 arguments:

  • $path | The path to the image
  • $name | (optional) The remote name of the file (attachment is renamed server side)
$message->attach($path, $name);

Embedding Inline Images

Embedding inline images into your e-mails is very easy. In your view you can use the embed method and pass it the path to the file. This will return a CID (Content-ID) which will be used as the source for the image. You can add multiple inline images to your message.

The embed method accepts 2 arguments:

  • $path | The path to the image
  • $name | (optional) The remote name of the file (attachment is renamed server side)
<body>
    <img src="{{ $message->embed($path, 'rename.png'); }}">
</body>

Example

Input
$data = [
	'img' => 'assets/img/example.png',
	'otherImg' => 'assets/img/foobar.jpg'
];

Mailgun::send('emails.welcome', $data, function ($message) {
I	$message->to('[email protected]', 'Recipient Name');
});
<body>
    <img src="{{ $message->embed($img) }}">
    <img src="{{ $message->embed($otherImg, 'custom_name.jpg') }}">
</body>
Output
<body>
    <img src="cid:example.png">
    <img src="cid:custom_name.jpg">
</body>

The $message variable is always passed to e-mail views by the Mailgun class.


Scheduling

Mailgun provides the ability to set a delivery time for emails up to 3 days in the future. To do this you can make use of the later method. While messages are not guaranteed to arrive at exactly at the requested time due to the dynamic nature of the queue, Mailgun will do it's best.

The later method works the same as the (default) send method but it accepts 1 extra argument. The extra argument is the amount of seconds (minutes, hours or days) from now the message should be send.

If the specified time exceeds the 3 day limit it will set the delivery time to the maximum of 3 days.

To send an email in 60 seconds from now you can do the following:

Mailgun::later(60, 'emails.welcome', $data, function ($message) {
    $message->to('[email protected]', 'John Doe')->subject('Welcome!');
});

When passing a string or integer as the first argument, it will interpret it as seconds. You can also specify the time in minutes, hours or days by passing an array where the key is the type and the value is the amount. For example, sending in 5 hours from now:

Mailgun::later(['hours' => 5], 'emails.welcome', $data, function($message) {
    $message->to('[email protected]', 'John Doe')->subject('Welcome!');
});

You can also pass a DateTime or Carbon date object.

Tagging

Sometimes it’s helpful to categorize your outgoing email traffic based on some criteria, perhaps for separate signup emails, password recovery emails or for user comments. Mailgun lets you tag each outgoing message with a custom tag. When you access the reporting page within the Mailgun control panel you can filter by those tags.

Warning: A single message may be marked with up to 3 tags. Maximum tag name length is 128 characters.

Mailgun allows you to have only limited amount of tags. You can have a total of 4000 unique tags.

To add a Tag to your email you can use the tag method.

You can add a single tag to an email by providing a string.

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->tag('myTag');
});

To add multiple tags to an email you can pass an array of tags. (Max 3)

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->tag(['Tag1', 'Tag2', 'Tag3']);
});

If you pass more than 3 tags to the tag method it will only use the first 3, the others will be ignored.

Campaigns

If you want your emails to be part of a campaign you created in Mailgun, you can add the campaign to a message with the campaign method. This method accepts a single ID string or an array of ID's (with a maximum of 3)

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->campaign('my_campaign_id');
	//or
	$message->campaign(['campaign_1', 'campaign_2', 'campaign_3']);
});

Tracking Clicks

Toggle clicks tracking on a per-message basis. Has higher priority than domain-level setting.

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->trackClicks(true);
	//or
	$message->trackClicks(false);
});

Tracking Opens

Toggle opens tracking on a per-message basis. Has higher priority than domain-level setting.

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->trackOpens(true);
	//or
	$message->trackOpens(false);
});

DKIM

Enable/disable DKIM signatures on per-message basis. (see Mailgun Docs)

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->dkim(true);
	// or
	$message->dkim(false);
});

Testmode

You can send messages in test mode. When you do this, Mailgun will accept the message but will not send it. This is useful for testing purposes.

Note: You are charged for messages sent in test mode.

To enabled testmode for all emails set the testmode option in the config file to true.

To enabled/disable testmode on a per message basis:

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->testmode(true);
	// or
	$message->testmode(false);
});

Alternative

Set the endpoint to Mailgun's Postbin. A Postbin is a web service that allows you to post data, which is then displayed through a browser. This allows you to quickly determine what is actually being transmitted to Mailgun's API.

Step 1 - Create a new Postbin.

Go to http://bin.mailgun.net. The Postbin will generate a special URL. Save that URL.

Step 2 - Configure the Mailgun client for using Postbin.

Tip: The bin id will be the URL part after bin.mailgun.net. It will be random generated letters and numbers. For example, the bin id in this URL, http://bin.mailgun.net/aecf68de, is "aecf68de".

In your config/mailgun.php, change the following

'api' => [
    'endpoint' => 'api.mailgun.net',
    'version' => 'v3',
    'ssl' => true
],

to:

'api' => [
    'endpoint' => 'bin.mailgun.net',
    'version' => 'abc1de23', // your Bin ID
    'ssl' => false
],

Now, all requests will be posted to the specified Postbin where you can review its contents.

Header

Add a custom header to your message

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->header($name, $value);
});

Data

Add custom data to your message

Mailgun::send('emails.welcome', $data, function ($message) {
	$message->data($key, $value);
});



Dependency Injection

All the examples in this document are using the Mailgun facade. The Mailgun service is registered in the Container as mailgun but you can also use the Interface Bogardo\Mailgun\Contracts\Mailgun for dependency injection in your app.

Example

namespace App\Http\Controllers;

class CustomController extends Controller
{

    /**
     * @var \Bogardo\Mailgun\Contracts\Mailgun
     */
    protected $mailgun;

    /**
     * @param \Bogardo\Mailgun\Contracts\Mailgun $mailgun
     */
    public function __construct(\Bogardo\Mailgun\Contracts\Mailgun $mailgun)
    {
        $this->mailgun = $mailgun;
    }
    
    public function index()
    {
        $this->mailgun->send($view, $data, $callback);
    }
}



Mailing lists

You can programmatically create mailing lists using Mailgun Mailing List API. A mailing list is a group of members (recipients) which itself has an email address, like [email protected]. This address becomes an ID for this mailing list.

When you send a message to [email protected], all members of the list will receive a copy of it.

Complete support of the Mailing List API is not included in this package. Though, you can communicate with the API using this package which should give you all the flexibility you need.

Some examples

For a full overview of all the available endpoints and the accepted parameters
please review the Official API Documentation

Get all lists (paginated)
Mailgun::api()->get("lists/pages");
Get a list by address
Mailgun::api()->get("lists/{$list}");
Create a new list
Mailgun::api()->post("lists", [
    'address'      => '[email protected]',
    'name'         => 'Developers',
    'description'  => 'Developers Mailing List',
    'access_level' => 'readonly'
]);
Update a member of a list
Mailgun::api()->put("lists/{$list}/members/{$member}", [
    'address'      => '[email protected]',
    'name'         => 'John Doe',
    'vars'         => json_encode(['age' => 35, 'country' => 'US']),
    'subscribed'   => 'no'
]);

Again, for a full overview of all the available endpoints and the accepted parameters
please review the Official API Documentation




OptInHandler

Utility for generating and validating an OptIn hash.

The typical flow for using this utility would be as follows:

Registration

  1. Recipient Requests Subscription
  2. Generate OptIn Link (with OptInHandler)
  3. Email Recipient OptIn Link

Validation

  1. Recipient Clicks OptIn Link
  2. Validate OptIn Link (with OptInHandler)
  3. Subscribe User
Example
$secretKey   = 'a_very_secret_key';

Registration

$listaddress = '[email protected]';
$subscriber  = '[email protected]';

$hash = Mailgun::optInHandler()->generateHash($listaddress, $secretKey, $subscriber);

var_dump($hash);
string 'eyJoIjoiODI2YWQ0OTRhNzkxMmZkYzI0MGJjYjM2MjFjMzAyY2M2YWQxZTY5MyIsInAiOiJleUp5SWpvaWNtVmphWEJwWlc1MFFHVjRZVzF3YkdVdVkyOXRJaXdpYkNJNkltMWhhV3hwYm1kc2FYTjBRR1Y0WVcxd2JHVXVZMjl0SW4wPSJ9' (length=180)

Validation

$result = Mailgun::optInHandler()->validateHash($secretKey, $hash);

var_dump($result);
array (size=2)
	'recipientAddress' => string '[email protected]' (length=21)
	'mailingList' => string '[email protected]' (length=23)
  
// Subscribe the user to the mailinglist
Mailgun::api()->post("lists/{$result['mailingList']}/members", [
    'address' => $result['recipientAddress'],
    'subscribed' => 'yes'
]);



Email Validation

Mailgun offers an email validation service which checks an email address on the following:

  • Syntax checks (RFC defined grammar)
  • DNS validation
  • Spell checks
  • Email Service Provider (ESP) specific local-part grammar (if available).

Single address

Validation a single address:

Mailgun::validator()->validate("[email protected]");

The validate method returns the following object:

stdClass Object
(
    [address] => [email protected]
    [did_you_mean] => 
    [is_valid] => 1
    [parts] => stdClass Object
        (
            [display_name] => 
            [domain] => bar.com
            [local_part] => foo
        )

)

It will also try to correct typo's:

Mailgun::validator()->validate("[email protected]")

returns:

stdClass Object
(
    [address] => [email protected]
    [did_you_mean] => [email protected]
    [is_valid] => 1
    [parts] => stdClass Object
        (
            [display_name] => 
            [domain] => gmil.com
            [local_part] => foo
        )

)

Multiple addresses

To validate multiple addresses you can use the parse method.

This parses a delimiter separated list of email addresses into two lists: parsed addresses and unparsable portions. The parsed addresses are a list of addresses that are syntactically valid (and optionally have DNS and ESP specific grammar checks) the unparsable list is a list of characters sequences that the parser was not able to understand. These often align with invalid email addresses, but not always. Delimiter characters are comma (,) and semicolon (;).

The parse method accepts two arguments:

  • addresses: An array of addresses or a delimiter separated string of addresses
  • syntaxOnly: Perform only syntax checks or DNS and ESP specific validation as well. (true by default)

Syntax only validation:

$addresses = 'Alice <[email protected]>,[email protected],example.com';
//or
$addresses = [
	'Alice <[email protected]>',
	'[email protected]',
	'example.com'
];

Mailgun::validator()->parse($addresses);

returns:

stdClass Object
(
    [parsed] => Array
        (
            [0] => Alice <[email protected]>
            [1] => [email protected]
        )

    [unparseable] => Array
        (
            [0] => example.com
        )

)

Validation including DNS and ESP validation:

$addresses = 'Alice <[email protected]>,[email protected],example.com';
Mailgun::validator()->parse($addresses, false);

returns:

stdClass Object
(
    [parsed] => Array
        (
        )

    [unparseable] => Array
        (
            [0] => Alice <[email protected]>
            [1] => [email protected]
            [2] => example.com
        )

)



License

The MIT License (MIT). Please see License File for more information.

mailgun's People

Contributors

andrejguran avatar bogardo avatar bul-ikana avatar chrisrollins65 avatar clementmas avatar codivist avatar davidngugi avatar dk-jessn avatar imadphp avatar jameskraus avatar jarbitlira avatar johannesschobel avatar manteca avatar nyholm avatar schneiderderek avatar sprocket 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mailgun's Issues

Lacking List features

Hey,
I like your package. kindly add List support (i.e. Adding to List, removing, updating etc)

Cheeers!

Lists not working for me.

I upgraded to the latest. - Installing bogardo/mailgun (v3.1.2)

Error
Call to undefined method Bogardo\Mailgun\Mailgun\Lists::member()

myCode
$mail = Mailgun::lists()->member("[email protected]", "[email protected]");
print_r($mail);

Also tried

myCode
Mailgun::lists()->members("[email protected]");

Error
Call to undefined method Bogardo\Mailgun\Mailgun\Lists::members()

No idea what is wrong.

Recipients from previous messages included in new messages

Hi again :)

There seems to be a bug when multiple emails are sent - in the example code below, the first email is correctly sent to [email protected], but the second email is incorrectly sent to both [email protected] and [email protected]. It should, of course, only be sent to [email protected]

Mailgun::send('emails.test', $data, function($message) {
            $message->to('[email protected]', 'Recipient One')->subject('Mailgun Test!');
});

Mailgun::send('emails.test', $data, function($message) {
            $message->to('[email protected]', 'Recipient Two')->subject('Mailgun Test!');
});

No issue, just a thanks!

Was super easy to drop this in and change the application Mail alias and update all our mailgun sends (SMTP is way too slow). Thanks! :)

The parameters passed to the API were invalid. Check your inputs!

I'm using laravel 4.2. I try bellow example, but it does not work. It occur bellow error.
"The parameters passed to the API were invalid. Check your inputs".

=> Code
$data = array(
'customer' => 'John Smith',
'url' => 'http://laravel.com'
);
Mailgun::send('emails.layout', $data, function($message)
{
$message->to('[email protected]', 'John Smith')->subject('Welcome!');
});

=> View file code
Hi {{ $customer }},
Please visit {{ $url }}

Attachments appearing inline

Attaching files to the email works . . . but the attachment also appears inline in the email.
This is the code used:
$message->attach(data['path'], $data['name']);
How to prevent it appearing inline?

The endpoint you've tried to access does not exist. Check your URL.

I've same issue. app develop using laravel 4.2, this package installed correctly. I'm working on local environment plan to send emails via mailgun API
Error is :

Mailgun \ Connection \ Exceptions \ MissingEndpoint 
The endpoint you've tried to access does not exist. Check your URL. 

Domain and API set in services.php

'mailgun' => array(
        'domain' => 'sandboxe786b43f2c3447fdaf02258fae929ab8.mailgun.org',
        'secret' => 'xxxxxx2833725df29b4ad6bbaadc1d9',)

can you help me to sort it out ?

The parameters passed to the API were invalid. Check your inputs!

Hello,
This is my code:

$to           = '[email protected]';
$subject      = 'offline';
$html_message = 'test offline';

$data = array(
    'customer' => 'John Smith',
    'url' => 'http://laravel.com'
);

Mailgun::send('mail', $data, function($message) use ($to,$subject)
{
    $message->to($to, 'John Smith')->subject($subject);
});

But it show error which is:
The parameters passed to the API were invalid. Check your inputs!
Can you explain ?
Thank you

Publish config get following error

I am using Laravel 4.2.*. I install this lib using composer and when i am trying to publish config i am getting following error

[InvalidArgumentException] There are no commands defined in the "vendor" namespace

How to solve this.

Bogardo/Mailgun and Password Reminders - Class 'Bogardo\Mailgun\MailgunApi' not found

I have used this package several times on a number of projects but this is the first time I am using with Password Reminders.

I followed the instructions given here: http://bogardo.com/mailgun-and-password-reminders/. I had issues with creating a namespace for the two new files but I had that resolved by using the autoload section of composer.json. Now, when I load the reminder form supply my e-mail address and submit (posts to password/reset), I get the following error and I do not get the password reset e-mail:

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR) Class 'Bogardo\Mailgun\MailgunApi' not found Open: ....../vendor/bogardo/mailgun/src/Bogardo/Mailgun/Mailgun.php

In the vendor folder, I can see the MailgunApi class here: Bogardo\Mailgun\Mailgun\MailgunApi. How do I resolve this issue? Let me know if you need more information.

I am using Laravel 4.2

Unable to get Campaigns working

Hi Bogardo,

Thanks for this brilliant tool but I am hoping you could give me an example of how to include a campaign id. I have had a number of attempts but I cannot get it right.

Neither of these work and I'm hoping you can point me in the right direction (I would have asked on the Laravel forum but it is moving and laravel.io isn't working).

$message->data('X-Mailgun-Campaign-Id', "{'o:campaign': '001_invitation_requests'}");
$message->data('o:campaign', '001_invitation_requests');
$message->data('X-Mailgun-Campaign-Id', '001_invitation_requests');

Thanks in advance and Thanks again for the repo.
John

Plain text emails

Hi,

With Laravel's Maill class you can send plain text emails like this:

Mailgun::send([], [], function($message) {

    });

Is there a way to do this with Mailgun::?
I get a setBody() error atm.

Wrong message id for email header causing emails to go straight to spam in some servers

Some emails that I send keep getting put into the spam folders of some email servers.
I poured through your docs to maybe pinpoint the issue, but could not.

I contacted Mailgun support to maybe shed some light on the issue, and they said it could be that my 'message-id' in my email header is wrong since it shows 'Message-Id: 282dc62aa198e497a5358f0aeeff56da@localhost. He mentioned that it should, in reality, be the same as the 'From:' address in the email.

Maybe this is a bug on your end? If not, please let me know common causes of this issue, if you have knowledge of them.

Question on Mailgun Endpoint URL

Hi,

First of all, thank you for this awesome package. Very easy to use!

However, I have a question. On my local machine, the sending of email works perfectly fine. However when I deployed it to my test server, I keep getting the ff. error:

Mailgun \ Connection \ Exceptions \ MissingEndpoint
The endpoint you've tried to access does not exist. Check your URL.

Is there anything that I miss or I have to configure when deploying?

Thanks,
Ridvan

Laravel 5

I realize laravel 5 is not yet released but we are getting very close. Would be really great to have the Mailgun package working with laravel 5 when it's released. Your package is such a great package. Many thanks for all you work. It's been a life saver.

Credentials incorrect

When you have time can you help me figure this out? I have installed this properly and now I can't get it to work. Says "Credentials Incorrect". I have published the package, filled out the config.php properly. Have no idea why it is not working.

Any ideas on what I could try?

Add support for queues

While working on the project I use Mailgun for, we've come across a slight issue.

Although Mailgun is a lot faster than using plain old SMTP to send emails, it still induces quite a delay at one stage of the process, basically we need to send custom emails out to (possibly) hundreds of people at one time.

One feature of Mail that this package doesnt replicate is Mail::queue. It would be super useful if that was able to be implemented. Is this something that would be possible?

Thanks for your work on this so far, it's helped in so many ways!

James

Composer does not like "v"

"bogardo/mailgun": "v3.0."
"bogardo/mailgun": "v2.
"

Should be

"bogardo/mailgun": "3.0."
"bogardo/mailgun": "2.
"

WebRoot]$ composer update
  [UnexpectedValueException]                                                  
  Could not parse version constraint v3.0.*: Invalid version string "v3.0.*"  

Method Mail::raw() not supported

Because Mail::raw() is not supported, it is mandatory that a view is passed, but in cases where you rendered the view before to execute some parsing function, like using CSSInline class, you cant just pass the parsed data to Mailgun::send.

Support Laravel 4.0 broken

With the latest update to the repo, support for laravel 4.0 has been dropped, en because there is no versioning or branches in your project, I am not able to install an earlier version. Can this be fixed?

Guzzle Dependency issues

It appears the bogardo/mailgun 4.0.* for Laravel 5 package has a conflict with one of my other packages.

My other package requires guzzlehttp/guzzle 6.1.1 but when I try to add this package I get a composer error:

  • Conclusion: don't install guzzlehttp/guzzle 6.1.x-dev
  • Conclusion: don't install guzzlehttp/guzzle 6.1.1
  • mailgun/mailgun-php v1.8 requires guzzlehttp/guzzle ~5.0 -> satisfiable by guzzlehttp/guzzle[5.3.x-dev].
  • Can only install one of: guzzlehttp/guzzle[6.1.0, 5.3.x-dev].

Can this be changed so your package has a MINIMUM requirement for guzzle 5.0. Having a newer version of Guzzle should not inhibit the installation of this package.

callback for Mailgun::send function if it is send or fails

sir please help me to have method so that i can know that the message are sent or fails so that i can apply callbacks response Example method "Mailgun::failures()"

Mailgun::send('emails.welcome', $data, function ($message) {
    $message->to('[email protected]', 'John Smith')->subject('Welcome!');
});
//i am happy if this Mailgun::failures will be added for easy callback response
if (Mailgun::failures()) {
    $result['success'] = 'false';
    $result['msg'] = 'There was an error while sending the email. Please try again';
}
else {
    $result['success'] = 'true';
    $result['msg'] = 'Email successfully sent';
}

return $result;

Guzzle 6

Hello I've been using this plug in without any issue. However, with my last update on my project where I'm using "guzzlehttp/guzzle:~6.1.1", "guzzlehttp/oauth-subscriber: dev-master" for Oauth. So now composer wouldn't install the plug in due to dependency version. So I wanted to ask you guys whether, you are planning to update your project any sooner, or any workaround.

Failed to install bogardo/mailgun, version 4.0.0

Hi,

I am using Laravel 5.2 with the latest version of guzzlehttp/guzzle [6.2.1]. When I try to install bogardo/mailgun, get the following error:

C:\xampp\php\php.exe C:/xampp/htdocs/project-name/composer.phar require bogardo/mailgun:4.0.0 -n --no-progress
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- mailgun/mailgun-php v1.8 requires guzzlehttp/guzzle ~5.0 -> satisfiable by guzzlehttp/guzzle[5.0.0, 5.0.1, 5.0.2, 5.0.3, 5.1.0, 5.2.0, 5.3.0, 5.3.1, 5.3.x-dev] but these conflict with your requirements or minimum-stability.
- bogardo/mailgun 4.0.0 requires mailgun/mailgun-php ^1.8 -> satisfiable by mailgun/mailgun-php[v1.8].
- Installation request for bogardo/mailgun 4.0.0 -> satisfiable by bogardo/mailgun[4.0.0].

Installation failed, reverting ./composer.json to its original content.

So, it seems that this package doesn't work with the latest version of guzzle... Can I expect this package to work with the latest version of guzzle any time soon, or I need to remove the current version and install 5.3.1?

SSL Certificate problem

By sending mail following error show:

RequestException in RequestException.php line 51: cURL error 60: SSL certificate problem: unable to get local issuer certificate

How to solve it?

[Insight] Commented code should not be commited - in src/Bogardo/Mailgun/Mailgun.php, line 100

in src/Bogardo/Mailgun/Mailgun.php, line 100

Commented out code reduces readability and lowers the code confidence for other developers. If it's common usage for debug, it should not be committed. Using a version control system, such code can be safely removed.

        $this->callMessageBuilder($callback, $this->message);

        $this->getMessage($view, $data);


        //dd($this->getMessageData());

        $this->mailgun()->sendMessage(Config::get('mailgun::domain'), $this->getMessageData(), $this->getAttachmentData());
    }

    /**

Posted from SensioLabsInsight

Batch Sending Mail Issue

Hi Bogardo,

I am trying to send a batch mail to multiple recipients at the same time using below code using Laravel framework.

Mailgun::send('emails.mudrush', $data, function($message) use($users)
{                   
    $message->subject('Last day to WIN free passes to The Mud Rush' );
    $message->to($users);
});

If you see $users array has all the emails of the users. Now the issue is every user is able to see all the other users emails.

But we don't want to visible all the users emails.

Support for recipient variables when batch-sending

From the manual: http://documentation.mailgun.com/user_manual.html#batch-sending when batch-sending, Mailgun only knows to send emails to individual recipients (i.e. one recipient in the 'to' field) when you use recipient variables. Batch sending has an advantage over using the Mailgun::send in a loop since there's only one API call with the former therefore less loading time for the user. And then there's the advantage of using the same to personalise the emails.
Could you kindly add this feature?

Great work!

size limits in the data array?

When sending emails, one of my email methods has a couple of object passed to the view along with a few variables. When I leave the data array empty or just pass the variables it sends just fine, when passing in the objects I get an InvalidCredentials error:

exception 'Mailgun\Connection\Exceptions\InvalidCredentials' with message 'Your credentials are incorrect.' in /srv/www/example.dev/deploy/match/vendor/mailgun/mailgun-php/src/Mailgun/Connection/RestClient.php:130

Yes I saw #33, but this is different, I have no problems with the validating emails, and emails are sending most of the time.

This one works everytime: (only 2 or 3 variables are passed through $data)

    private function sendTo(User $user, $subject, $view, $data = [], $from = '') {
        return Mailgun::send($view, $data, function ($message) use ($user, $subject, $from) {
            if($from) {
                $message->from($from);
            }
            $message->to($user->email, $user->full_name)
                ->subject($subject);
        });
    }

This one does NOT work: (two object and 3 variables are being passed to $data)

    private function sendToAdmin($adminEmail, $subject, $view, $data = []) {
        return Mailgun::send($view, $data, function ($message) use ($adminEmail, $subject) {
            $message->to($adminEmail)
                ->subject($subject);
        });
    }

when changing the $data to an empty array in the send method it sends.

Additional config

I recommend adding one small thing to the configuration, i.e.

Add the following alias to the aliases array in your app/config/app.php file.
'Mailgun' => 'Bogardo\Mailgun\Facades\Mailgun'

It's easier to "use Mailgun" this way. Thanks.

Sending to multiple recipients

What's the best way to send an email to multiple recipients?

Ideally, I'd like to be able to pass an array of email addresses to the $message->to() function, like you can using Laravel's default Mail object.

Laravel 5.3 and Mailable Support

Laravel 5.3 is out. =)

I like their new Mailables feature. Mail::to($request->user())->send(new OrderShipped($order));

Mailgun documentation doesn't suggest this is feasible yet. Thought I'd mention it.

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.