Link to home
Start Free TrialLog in
Avatar of B O
B O

asked on

I am trying to install/use mailGun for my project but I have problems with understanding how to use SMTP

I have issues creating a mailing system, it has been recommended to me to use mailGun.
But it is kind of complex for me to understand whick pieces I need to install/ use to have a decent mailing system.
I have already installed strawberry perl.

I tried installing it by using some commands from:
http://www.jetmore.org/john/code/swaks/
https://www.cpan.org/modules/INSTALL.html

But I am really confused now

Thank you in advance for taking the time to read my question

User generated image

User generated image


Avatar of David Favor
David Favor
Flag of United States of America image

Looks like wherever you placed the swaks script, the path where swaks lives is outside your normal path.

Place the swaks script in a directory in your path or run swaks using an absolute path.
Have you had a look at the documentation page for this

From the MailGun API Page
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = Mailgun::create('PRIVATE_API_KEY', 'https://API_HOSTNAME');
$domain = "YOUR_DOMAIN_NAME";
$params =  array(    'from'    => 'Excited User <YOU@YOUR_DOMAIN_NAME>',    'to'      => array('bob@example.com, alice@example.com'),    'subject' => 'Hey %recipient.first%',    'text'    => 'If you wish to unsubscribe, click http://example.com/unsubscribe/%recipient.id%',    'recipient-variables' => '{"bob@example.com": {"first":"Bob", "id":1},
                               "alice@example.com": {"first":"Alice", "id": 2}}'
);

# Make the call to the client.
$result = $mgClient->messages()-send($domain, $params);

Open in new window

Avatar of B O
B O

ASKER

Hi thank you for replying,

I have looked at it, but not everything is so clear to me

Now I got a error and looked a the documentation and cant figure out what exactly I did wrong.


Fatal error: Uncaught Mailgun\Exception\HydrationException: Error (4) when trying to json_decode response in C:\xampp\htdocs\blog-app\vendor\mailgun\mailgun-php\src\Hydrator\ModelHydrator.php:40 Stack trace: #0 C:\xampp\htdocs\blog-app\vendor\mailgun\mailgun-php\src\Api\HttpApi.php(76): Mailgun\Hydrator\ModelHydrator->hydrate(Object(GuzzleHttp\Psr7\Response), 'Mailgun\\Model\\M...') #1 C:\xampp\htdocs\blog-app\vendor\mailgun\mailgun-php\src\Api\Message.php(63): Mailgun\Api\HttpApi->hydrateResponse(Object(GuzzleHttp\Psr7\Response), 'Mailgun\\Model\\M...') #2 C:\xampp\htdocs\blog-app\includes\mail.incl.php(64): Mailgun\Api\Message->send('https://api.mai...', Array) #3 {main} thrown in C:\xampp\htdocs\blog-app\vendor\mailgun\mailgun-php\src\Hydrator\ModelHydrator.php on line 40 


#/ Include the Autoloader (see "Libraries" for install instructions)
require __DIR__ . '/../vendor/autoload.php';
use Mailgun\Mailgun;


// Loads .env file token
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();


$API_key  = $_ENV['MAILGUN_TOKEN'];


// var_dump('APIKEY = ', $API_key);


// $search = $_POST['search'];


# Instantiate the client.
$mgClient = Mailgun::create($API_key, 'https://api.eu.mailgun.net');
// $mgClient = new Mailgun();
$domain = "https://api.mailgun.net/v3/sandbox286233abbd8f4367922b1b611ca0925a.mailgun.org";
$params =  array(   'from'    => 'Excited User <YOU@gmail.com>',    
                    'to'      => array('bo@gmail.com'),    
                    'subject' => 'Hey %recipient.first%',    
                    'text'    => 'If you wish to unsubscribe, click http://example.com/unsubscribe/%recipient.id%',    
                    'recipient-variables' => '{"bo@gmail.com": {"first":"Bob", "id":1},
                               "tkbotch@gmail.com": {"first":"Alice", "id": 2}}'
);


#user input
// $message_body = " ";
$to_email = 'bo@gmail.com';
// $subject = $_POST["full_name"];
// $message_body .= "Contact No: ".$_POST["phone_number"]."\n"; 
// $message_body .= "Message: ".$_POST["user_question"]."\n";
// $headers = 'From: ' . $_POST["email_adress"];




$response = array(
    'status' => 0,
    'message' => 'Form submission falied, please try again'
);


function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}




if (isset($_POST['submit_question'])) {


//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);


var_dump($mgClient);


if ($secure_check == false) {
    $response['message'] = "Invalid input";
    echo $response['message'];
} else { //send email 
    # Make the call to the client.
    $result = $mgClient->messages()-send($domain, $params);
    // $result = $mgClient->messages()->send($domain, array(
    //     'from'   => 'Excited User <mailgun@YOUR_DOMAIN_NAME>',
    //     'to' => 'bo <bo@gmail.com>',
    //     'subject' => 'Hello',
    //     'text'   => 'Testing some Mailgun awesomness!'
    // ));
}#end if else secure_check
}#end submit question upload

Open in new window



Avatar of B O

ASKER

I think something wrong with the domain name I am using

I tried

https://api.mailgun.net/v3/sandbox286233abbd8f4367922b1b611ca0925a.mailgun.org

https://api.eu.mailgun.net/

https://api.eu.mailgun.net/v3 
I just did a test with this code. No problems
define('MAILGUN_API_KEY', 'YOUR PRIVATE KEY HERE');
define('MAILGUN_API_URL', 'YOUR API URL'); // If not US
define('MAILGUN_DOMAIN', 'YOUR SENDING DOMAIN');

require 'vendor/autoload.php';
use Mailgun\Mailgun;

$mg = Mailgun::create(MAILGUN_API_KEY, MAILGUN_API_URL);

// Now, compose and send your message.
$domain = MAILGUN_DOMAIN;
$params =  [
    'from'    => 'Excited User <test@domain.com>',
    'to'      => 'someone@email.com',
    'subject' => 'Test from mailgun',
    'text'    => 'Sample text'
];

$mg->messages()->send($domain, $params);

Open in new window

The only thing I had to do was whitelist the IP of my sending PC.
MailGun Dashboard => Settings => API Keys => API Security - scroll down to the bottom.

Other than that.

1. composer init (create a project)
2. composer require  mailgun/mailgun-php kriswallsmith/buzz nyholm/psr7
3. Create index.php as per above
4. Update index.php with your variables
php index.php

Open in new window




For the above code your defines would be as follows (remembering to change the XXXXXXXXX for the correct number - NOTE you should not post actual domains or other defining information in your questions)
define('MAILGUN_DOMAIN', 'sandbox286233abbd8f4367922b1b61XXXXXXXX.mailgun.org');
define('MAILGUN_API_URL', 'https://api.eu.mailgun.net/v3/');

Open in new window

Avatar of B O

ASKER

Thank you for replying
I white listed my Ip adress

I did the following in C:\xampp\htdocs\blog-app\vendor\mailgun\mailgun-php\src\index.php

<?php
// Loads .env file token
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();


$API_key  = $_ENV['MAILGUN_TOKEN'];


require 'vendor/autoload.php';
use Mailgun\Mailgun;




define('MAILGUN_API_KEY', $API_key);


define('MAILGUN_DOMAIN', 'sandbox286233abbd8f4367922b1b611ca0925a.mailgun.org');
define('MAILGUN_API_URL', 'https://api.eu.mailgun.net/v3/');

Open in new window


mail.incl.php
<?php
require __DIR__ . '/../vendor/autoload.php';
use Mailgun\Mailgun;


// Loads .env file token
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();


$API_key  = $_ENV['MAILGUN_TOKEN'];




define('MAILGUN_API_KEY', $API_key);
define('MAILGUN_API_URL', 'https://api.mailgun.net/v3/sandbox286233abbd8f4367922b1b611ca0925a.mailgun.org'); // If not US
define('MAILGUN_DOMAIN', 'sandbox286233abbd8f4367922b1b611ca0925a.mailgun.org');


$mg = Mailgun::create(MAILGUN_API_KEY, MAILGUN_API_URL);


// Now, compose and send your message.
$domain = MAILGUN_DOMAIN;
$params =  [
    'from'    => 'Excited User <test@domain.com>',
    'to'      => 'bo@email.com',
    'subject' => 'Test from mailgun',
    'text'    => 'Sample text'
];


$mg->messages()->send($domain, $params);

Open in new window


White listed Ip
User generated image
browser after upload
User generated image

Where are your API Keys?

For this to work you need a Private API key?

Where does this come from?
$API_key  = $_ENV['MAILGUN_TOKEN'];

Open in new window


That value should be shown on your API keys screen. I am not seeing those populated?

Avatar of B O

ASKER

Yes I have a dot env file which i use to hide API key,
I taught to do it this way when working with php


.env file


MAILGUN_TOKEN=53600d2a657f20f9f5b071d4XXXXXXXXXXXXXXXXX

Open in new window

Where does that token come from? If it is not from the API Keys page then it is the wrong token.
Avatar of B O

ASKER

I got the API key and url from the website

User generated image
Avatar of B O

ASKER

I thaught sending mail suppose to be like the most basic thing to do
I thaught, I really didnt expect it to be complicated like this :P
You said, "I thought sending mail suppose to be like the most basic thing to do".

Correct, if you're sending SMTP mail.

Working with APIs tends to inject many complexities.

So...

MailGun SMTP != MailGun API

2x different beasts.
Avatar of B O

ASKER

OKe Thank you,

I am trying to figure out how to configure a mailgun SMTP mail system.

I am now looking at this page, maybe you could guide me a little bit through
https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-smtp
It shouldn't be that complicated. If you look at my earlier post it shows the exact steps I used to connect and send an email. Took 5 min.

The main complexity is the security - which is understandable. The only difference between my code and yours is you are using the Sandbox domain. I know from when I started at Mailgun I had endless problems trying to use this - they make it difficult. Once we upgraded and setup our own domain it worked like a charm.

I suspect your problem is you have not setup Authorised users for the sandbox domain. Take a read of this article and let me know if it solves your problem. https://help.mailgun.com/hc/en-us/articles/217531258

Failing that you might want to consider upgrading. You will need to at some point if you are going to use the service. You get 5K free emails during the 3 month free trial period - should be enough to evaluate the service.
Avatar of B O

ASKER

Hi Thank you for answering,

I think there is really something wrong with my credentails,
I updated my account and set up DNS settings.
Now I have created a js file with intent to send mail thru mailGun

I installed:
- MailGun: https://mailgun.com
- NodeMailer: https://nodemailer.com/usage/ 

I also resetted my password But still got errors about credentials.

User generated image
User generated image
User generated imagemail.js
// require('dotenv').config();

const nodemailer = require('nodemailer');
const mailGun = require('nodemailer-mailgun-transport');
const log = console.log;

// Step 1
const auth = {
    auth: {
        api_key:'key-788e7898fd079553abb30da1f9e93129', // TODO: 
        domain:'istanbulhair.teddybotchway.nl' // TODO:
    }
};

// Step 2
let transporter = nodemailer.createTransport( mailGun(auth) );


// Step 3
let mailOptions = {
    from: 'user <abc@gmail.com>', // TODO: email sender
    to: 'tkbotch@gmail.com', // TODO: email receiver
    subject: 'Nodemailer - Test',
    text: 'Wooohooo it works!!'
};

// Step 4
transporter.sendMail(mailOptions, (err, data) => {
    if (err) {
        return log('Error occurs');
    }
    return log('Email sent!!!');
});

// const api_key = 'key-788e7898fd079553abb30da1f9e93129';
// const mailgun = require("mailgun-js");
// const DOMAIN = 'istanbulhair.teddybotchway.nl';
// const mg = mailgun({apiKey: api_key, domain: DOMAIN});
// const data = {
//  from: 'Excited User <me@samples.mailgun.org>',
//  to: 'tkbotch@gmail.com, info@istanbulhair.teddybotchway.nl',
//  subject: 'Hello',
//  text: 'Testing some Mailgun awesomness!'
// };
// mg.messages().send(data, function (error, body) {
//  console.log(body);
// });

 
<?php
#/ Include the Autoloader (see "Libraries" for install instructions)
require __DIR__ . '/../vendor/autoload.php';
use Mailgun\Mailgun;

// Loads .env file token
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

$API_key  = $_ENV['MAILGUN_TOKEN'];

// var_dump('APIKEY = ', $API_key);

// $search = $_POST['search'];

# Instantiate the client.
$mgClient = Mailgun::create($API_key, 'https://api.eu.mailgun.net');
// $mgClient = new Mailgun();
$domain = "istanbulhair.teddybotchway.nl";
$params =  array(   'from'    => 'Excited User <YOU@gmail.com>',    
                    'to'      => array('tkbotch@gmail.com'),    
                    'subject' => 'Hey %recipient.first%',    
                    'text'    => 'If you wish to unsubscribe, click http://example.com/unsubscribe/%recipient.id%',    
                    'recipient-variables' => '{"tkbotch@gmail.com": {"first":"Bob", "id":1},
                               "tkbotch@gmail.com": {"first":"Alice", "id": 2}}'
);

#user input
// $message_body = " ";
$to_email = 'tkbotch@gmail.com';
// $subject = $_POST["full_name"];
// $message_body .= "Contact No: ".$_POST["phone_number"]."\n"; 
// $message_body .= "Message: ".$_POST["user_question"]."\n";
// $headers = 'From: ' . $_POST["email_adress"];


$response = array(
    'status' => 0,
    'message' => 'Form submission falied, please try again'
);

function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}


if (isset($_POST['submit_question'])) {

//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);

// var_dump($mgClient);

if ($secure_check == false) {
    $response['message'] = "Invalid input";
    echo $response['message'];
} else { //send email 
    # Make the call to the client.
    $result = $mgClient->messages()->send($domain, $params);
    // $result = $mgClient->messages()->send($domain, array(
    //     'from'   => 'Excited User <mailgun@YOUR_DOMAIN_NAME>',
    //     'to' => 'T <tkbotch@gmail.com>',
    //     'subject' => 'Hello',
    //     'text'   => 'Testing some Mailgun awesomness!'
    // ));
}#end if else secure_check
}#end submit question upload
@BO,

Rather than deleting could you instead post how you got it fixed. That way others who might have the same problem can benefit from your insights.
This question contains a plethora of useful MailGun config info which is unique to this question.

Question should be kept for future reference by people setting up MailGun.
Avatar of B O

ASKER

Alright here it is
I tried deleting it because I could post a new question,
there was some type of error
So I taught be deleting the question would enable me to make a new question

// Using Awesome https://github.com/PHPMailer/PHPMailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

require __DIR__ . '/vendor/autoload.php';
// Loads .env file token

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// require 'PHPMailerAutoload.php';
if (isset($_POST['submit_question'])) {

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.eu.mailgun.org';                     // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'postmaster@istanbulhairhere.nl';   // SMTP username
$mail->Password = $_ENV['MAILGUN_TOKEN'];                         // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, only 'tls' is accepted

$mail->From = $_POST["email_adress"];
$mail->FromName = 'Mailer';
$mail->addAddress('istanbulmail@gmail.com');                 // Add a recipient

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters

$mail->Subject = $_POST["full_name"];
$mail->Body    .=  'Contact No: '.$_POST["phone_number"]. '\n';
$mail->Body    .= 'Message: '.$_POST['user_question'].'\n';

    if(!$mail->send()) {
        echo 'Message could not be sent.';
        echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        echo 'Message has been sent';
    }
}

Open in new window



Tip: Use SWAKS first to test your host/port/user/pass to ensure these are all correct.

If they're incorrect, no amount of mucking about with PHP will fix this problem.

SWAKS - 1st.

PHP - 2nd.
Avatar of B O

ASKER

Thank you for your reply
I looked into Swaks but got stuck a lil with understanding that so I used the code I uploaded.
But I would appreciate it if you could show me how to use swaks as I couldnt figure it out before
I have not used the program David points out, but that is really just going to add more confusion.  The reason is you are using the API and not SMTP as per your post here https://www.experts-exchange.com/questions/29210385/I-am-trying-to-install-use-mailGun-for-my-project-but-I-have-problems-with-understanding-how-to-use-SMTP.html#a43257155 I would ignore that for now because I don't believe it comes into play.

Also, be sure to reset all of your authorization's because you have posted it here in public open for others to view and use. 
Avatar of B O

ASKER

Thank you I resetted the authorizations
ASKER CERTIFIED SOLUTION
Avatar of B O
B O

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial