Jump to content

Send email with mailjet


pohrebacek

Recommended Posts

Hi,

im trying to make webpage where user type their email, subject and message in html form and then hit submit. After that I want to send that form to my email address. I'm using mailjet.com as SMTP server.

When I hit submit on my page, I get response that email has been sent, but none emaill has arrived.

Any ideas on how to make it work? Maybe some other scripts or ways to achieve it? Please help.

my php script:

<?php

use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php';

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $mail = new PHPMailer(true);    

    try {        
        //Server settings        
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output        
        $mail->isSMTP();                                            //Send using SMTP        
        $mail->Host       = 'in-v3.mailjet.com';                     //Set the SMTP server to send through        
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication        
        $mail->AuthType = 'LOGIN';        
        $mail->Username   = 'API KEY';                     //SMTP username        
        $mail->Password   = 'SECRET KEY';                               //SMTP password        
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;            //Enable implicit TLS encryption        
        $mail->Port       = 587;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`        

        //Recipients        
        $mail->setFrom($_POST["email"]);        
        $mail->addAddress('MY EMAIL ADDRESS');     //Add a recipient        
        //$mail->addAddress('MY EMAIL ADDRESS');               //Name is optional        
        //$mail->addReplyTo('info@example.com', 'Information');        
        //$mail->addCC('cc@example.com');        
        //$mail->addBCC('bcc@example.com');        

        //Attachments        
        //$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments        
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name        

        //Content        
        $mail->isHTML(true);                                  //Set email format to HTML        
        $mail->Subject = $_POST["subject"];        
        $mail->Body    = $_POST["msg"];        
        $mail->AltBody = $_POST["msg"];        
        $mail->send();        
        echo 'Message has been sent';        

        //header("Location: ./");    
    }

    catch (Exception $e)
    {        
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

 

Edited by Psycho
Formatted code content
Link to comment
Share on other sites

9 hours ago, pohrebacek said:

<?php

use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP;

use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php';

but you are using PHP Mailer. Interesting predicament.

<?php
require 'vendor/autoload.php';
use \Mailjet\Resources;
...

i tried a Google search to find a good example:

https://github.com/mailjet/mailjet-apiv3-php?tab=readme-ov-file#make-your-first-call

Link to comment
Share on other sites

On 9/20/2024 at 5:19 PM, gw1500se said:

You need to use the MailJet API.

when i use MailJet API I get this error: Failed to send email. Error: Unauthorized array(0) { }

 

 

my code:

 

<?php

/*

This call sends a message to one recipient.

*/

require 'vendor/autoload.php';

use \Mailjet\Resources;

$mj = new \Mailjet\Client(getenv('MY_APIKEY'), getenv('MY_SECRETKEY '),true,['version' => 'v3.1']);

if($_SERVER['REQUEST_METHOD'] == 'POST') {

$body = [

    'Messages' => [

        [

            'From' => [

                'Email' => $_POST["email"],

                'Name' => "Mailjet Pilot"

            ],

            'To' => [

                [

                    'Email' => "MY_EMAIL",

                    'Name' => "passenger 1"

                ]

            ],

            'Subject' => $_POST["subject"],

            'TextPart' => $_POST["msg"],

            'HTMLPart' => $_POST["msg"]

        ]

    ]

];

$response = $mj->post(Resources::$Email, ['body' => $body]);

if ($response->success()) {

    $data = $response->getData();

    echo "Email was sent successfully.\n";

    var_dump($data);

} else {

    echo "Failed to send email. Error: " . $response->getReasonPhrase() . "\n";

    var_dump($response->getData());

}

}

?>

Link to comment
Share on other sites

19 minutes ago, gw1500se said:

Please use the code icon (<>) and select PHP for your code. It formats the code to make it easier to read.

Oh my bad, I'm new here

 

 

<?php

/*

This call sends a message to one recipient.

*/

require 'vendor/autoload.php';

use \Mailjet\Resources;

$mj = new \Mailjet\Client(getenv('MY_APIKEY'), getenv('MY_SECRETKEY '),true,['version' => 'v3.1']);

if($_SERVER['REQUEST_METHOD'] == 'POST') {

$body = [

    'Messages' => [

        [

            'From' => [

                'Email' => $_POST["email"],

                'Name' => "Mailjet Pilot"

            ],

            'To' => [

                [

                    'Email' => "MY_EMAIL",

                    'Name' => "passenger 1"

                ]

            ],

            'Subject' => $_POST["subject"],

            'TextPart' => $_POST["msg"],

            'HTMLPart' => $_POST["msg"]

        ]

    ]

];

$response = $mj->post(Resources::$Email, ['body' => $body]);

if ($response->success()) {

    $data = $response->getData();

    echo "Email was sent successfully.\n";

    var_dump($data);

} else {

    echo "Failed to send email. Error: " . $response->getReasonPhrase() . "\n";

    var_dump($response->getData());

}

}

?>

 

Link to comment
Share on other sites

1. unauthorized error = You have specified an incorrect Api Key / API Secret Key.

2. To use the Mailjet Email API, you need to: Create a Mailjet account, then retrieve your API and Secret keys. They will be used for authentication purposes.

have you created an account? just trying to clarify.

if you have valid api credentials, then Initialize your Mailjet Client:
https://github.com/mailjet/mailjet-apiv3-php?tab=readme-ov-file#authentication

Link to comment
Share on other sites

24 minutes ago, jodunno said:

1. unauthorized error = You have specified an incorrect Api Key / API Secret Key.

2. To use the Mailjet Email API, you need to: Create a Mailjet account, then retrieve your API and Secret keys. They will be used for authentication purposes.

have you created an account? just trying to clarify.

if you have valid api credentials, then Initialize your Mailjet Client:
https://github.com/mailjet/mailjet-apiv3-php?tab=readme-ov-file#authentication

Yes I have mailjet account and I'm using my real API keys in my code.

I tried to Initialize my Mailjet Client like you said, but now I'm getting different error, Failed to send email.

Error:

At least FromEmail or Sender must be provided array(0) { }

 

 

But althrough i can see my from email in array when i echo it, I still get this error.

 

 

<?php
/*
This call sends a message to one recipient.
*/


require 'vendor/autoload.php';
use \Mailjet\Resources;

$apikey = 'MY_APIKEY';
$apisecret = 'MY_APISECRETKEY';

$mj = new \Mailjet\Client($apikey, $apisecret);

if($_SERVER['REQUEST_METHOD'] == 'POST') {
$body = [
    'Messages' => [
        [
            'From' => [
                'Email' => $_POST["email"],
                'Name' => "Mailjet Pilot"
            ],
            'To' => [
                [
                    'Email' => "MY_EMAIL",
                    'Name' => "passenger 1"
                ]
            ],
            'Subject' => $_POST["subject"],
            'TextPart' => $_POST["msg"],
            'HTMLPart' => $_POST["msg"]
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
echo print_r($body);
if ($response->success()) {
    $data = $response->getData();
    echo "Email was sent successfully.\n";
    // Zobraz nebo zpracuj data podle potřeby
    var_dump($data);
} else {
    echo "Failed to send email. Error: " . $response->getReasonPhrase() . "\n";
    // Zobraz nebo zpracuj chybové informace
    var_dump($response->getData());
}
}
?>

 

Link to comment
Share on other sites

I do not use Mailjet but i have discovered that other users have had a similar problem with the api. try specifying the api

$mj = new \Mailjet\Client($apikey, $apisecret, true,['version' => 'v3.1']);

otherwise, i have to run a setup myself to see if i can make it work.

Link to comment
Share on other sites

13 hours ago, pohrebacek said:
            'From' => [
                'Email' => $_POST["email"],
                'Name' => "Mailjet Pilot"
            ],
            'To' => [
                [
                    'Email' => "MY_EMAIL",
                    'Name' => "passenger 1"
                ]

i do not use Mailjet but i read an article and the author suggests that your email is to be placed in the From array and the post email in the To array. It doesn't make sense to me but the author of the article uses this method in his form submission code.

Link to comment
Share on other sites

I don't see where you've posted your form code in the thread - just to confirm that you've got all the data you think you have, put the following right after the `if($_SERVER['REQUEST_METHOD'] == 'POST') {` line:

die('<pre>'.var_export($_POST, true).'</pre>');

Then check to make sure there's keys for email, subject, and msg in the $_POST array.

Link to comment
Share on other sites

On 9/24/2024 at 5:36 AM, jodunno said:

I do not use Mailjet but i have discovered that other users have had a similar problem with the api. try specifying the api

$mj = new \Mailjet\Client($apikey, $apisecret, true,['version' => 'v3.1']);

otherwise, i have to run a setup myself to see if i can make it work.

Thanks, there aren't any errors anymore, but I still can't see any email that was sent thanks to my script.

I added this line and switched "from" and "to" email but it still doesn't work.

Link to comment
Share on other sites

On 9/24/2024 at 2:06 PM, maxxd said:

I don't see where you've posted your form code in the thread - just to confirm that you've got all the data you think you have, put the following right after the `if($_SERVER['REQUEST_METHOD'] == 'POST') {` line:

die('<pre>'.var_export($_POST, true).'</pre>');

Then check to make sure there's keys for email, subject, and msg in the $_POST array.

Everything is fine according to this.

Link to comment
Share on other sites

If you're not getting any errors and everything in the $_POST array is where and what you expect, it sounds like things are working so far as you can control. I don't use MailJet, but I assume there's a dashboard where you can see emails sent through your account, or at least how many were sent per day. It's possible something is catching it between send and receive, but again you'd need to verify they're actually getting sent through the service first.

Link to comment
Share on other sites

You also need to authorize any email addresses. You add that address to the contacts list on MailJet which will send an authorization email. You need to click on the link in that email to authorize it, then you should be good to go.

  • Like 1
Link to comment
Share on other sites

I found out it didn't work beacause my mailjet account was temporarily blocked.

Here is code that works for me:

<?php


require 'vendor/autoload.php';
use \Mailjet\Resources;

$apikey = 'MY_APIKEY';
$apisecret = 'MY_SECRETKEY';


$mj = new \Mailjet\Client($apikey, $apisecret, true,['version' => 'v3.1']);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$body = [
    'Messages' => [
        [
            'From' => [
                'Email' => "EMAIL",
                'Name' => "Mailjet Pilot"
            ],
            'To' => [
                [
                    'Email' => "EMAIL",
                    'Name' => "passenger 1"
                ]
            ],
            'Subject' => $_POST["subject"],
            'TextPart' => $_POST["msg"],
            'HTMLPart' => $_POST["msg"]
        ]
    ]
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
if ($response->success()) {
    $data = $response->getData();
    echo "Email was sent successfully.\n";
    var_dump($data);
} else {
    echo "Failed to send email. Error: " . $response->getReasonPhrase() . "\n";
    var_dump($response->getData());
}
}
?>

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.