Sending content of a form to one specific e-mail adress

Hi,

I am working on this page: https://kroweb.dk/gfdev/kontakt/

The form is a contact form which is meant to send its content to one specific e-mail address on submit.

The form:
<form id="myForm" action="send-email.php" method="post">  

                     <?php if (isset($_SESSION['response'])): ?>
                     <?php
                     $response = json_decode($_SESSION['response']);
                     unset($_SESSION['response']);
                     ?>

                     <div class="message <?php echo $response->success ? "success" : "error" ?>">
                      <?php echo $response->message; ?>
                    </div>
                  <?php endif ?>


                  <p class="form-input-top">Navn</p>
                  <input class="form-input" type="text" placeholder="Skriv dit navn" name="navn" id="navn" value="" required><br>

                  <p class="form-input-top">E-mail</p>
                  <input class="form-input" type="text" placeholder= "Skriv din e-mail adresse her" name= "e-mail" id="e-mail" value= "" required><br>

                  <p class="form-input-top">Emne</p>
                  <input class="form-input" type="text" placeholder= "Skrive dit emne her" name= "emne" id="emne" value="" required><br>

                  <p class="form-input-top">Besked</p>
                  <textarea class="form-input" type="textarea" placeholder= "Skriv din besked her" name= "besked" id="besked" value="" required></textarea><br>

                  <input type="text" placeholder= "Kort" name= "kort" id="Kort" value=" &#xf041; ️"  hidden>

                  <div id="buttons">
                      <input class="form-button" type="submit" id= "send-btn" value="Send">

                      <input class="form-button" type="reset" id= "reset-btn" value="Fortryd">
                  </div>

                </form>

Open in new window


The "action" file (send-email.php)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start the session
session_start();

$navn = $_POST['navn'];
$email = $_POST['e-mail'];
$emne = $_POST['emne'];
$besked = $_POST['besked'];

// Prevent direct access to the script
if (!isset($_POST['navn'])) die("Access Denied!");


// Code that sends the content of the form to one email adress




if (null !== ($_POST['navn'] && $_POST['e-mail'] && $_POST['emne'] && $_POST['besked'] )): // should be changed to something like if(the e-mail is actually sent):

$response = array(
	"message" => "Din-email er sendt"
	);

else: 

	$response = array(
		"success" => 0,
		"message" => "Noget gik galt. Prøv igen."
		);  

endif;  

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window


I need a little help to create the code that actually sends this e-mail, and to setup the if statement below to check if the e-mail is actually sent.

If anybody has ideas I am all ears :)
Peter KromanSales ExecutiveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Hey Peter,

Depending on your needs, there are a couple of options. Probably the most robust way, with lots of options, is to use a pre-built library. PHPMailer is a very popular and an easy one to use. You can find all the info you need here: https://github.com/PHPMailer/PHPMailer. This takes an Object Oriented approach to sending your email.

If you want to roll your own solution and only have very simple needs, then PHP has built in mail capabilities with the mail() function. You can read all about it here: http://php.net/manual/en/function.mail.php.

A very simple example follows:

$message = "This is an email message";
$sent = mail('chris@example.com', 'My Email Subject', $message);
if ($sent) {
    // email was sent OK!
}

Open in new window

Whichever method you choose, they both return a a boolean (true/false) when you send the mail so you can check whether it sent or not.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Chris,

Looking ....
0
Peter KromanSales ExecutiveAuthor Commented:
OK. Tried this code. It says (in the message) that the mail is sent - but nothing seems to be sent. What am I doing wrong?

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start the session
session_start();

$navn = $_POST['navn'];
$email = $_POST['e-mail'];
$emne = $_POST['emne'];
$besked = $_POST['besked'];

// Prevent direct access to the script
if (!isset($_POST['navn'])) die("Access Denied!");


// Code that sends the content of the form to one email adress
$message = $navn && $email && $emne && $besked;
$sent = mail('peter_kroman@genealogiskforum.dk', 'Henvendelse via Kontakt form på Gf', $message);



if ($sent): 

$response = array(
	"message" => "Din-email er sendt"
	);

else: 

	$response = array(
		"success" => 0,
		"message" => "Noget gik galt. Prøv igen."
		);  

endif;  

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Chris StanyonWebDevCommented:
Hey Peter,

Fundamentally, you're not doing anything wrong. The mail() function will return true if it successfully passed the email off to the mail transport agent (SMTP) on your server. If the transport agent then fails to send the message, you won't know about it. This could be down to how your server is configured. You should check with your host on whether sendmail is configured correctly. You may also need to check the php.ini file which will contain some of the config settings. It may also be that the email you're sending needs additional info - this is provided by adding headers to the email:

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
    'From' => 'webmaster@example.com',
    'Reply-To' => 'webmaster@example.com'
    'X-Mailer' => 'PHP/' . phpversion()
);

mail($to, $subject, $message, $headers);

Open in new window

It's for this reason that using something like PHPMailer is often preferred over the standard mail() function, and I'd certainly recommend you take that route. You get to set the options in a much more friendly way.
0
Peter KromanSales ExecutiveAuthor Commented:
I'll dive into PHP mailer :)
0
Peter KromanSales ExecutiveAuthor Commented:
Well - now I have got the phpmailer folder and composer.phar uploaded like this .

resources folder with composer and phpmailer
And what to do next??

It says everywhere that it is SO easy to install with Composer. But it is not very easy to guess how you do it when this is not something you have done before :)

I simply don't understand the explanations here: https://github.com/PHPMailer/PHPMailer.

So I need some help to get phpmailer set up and working.

Please :) :)
0
Chris StanyonWebDevCommented:
OK Peter,

That looks like you've downloaded the PHPLibrary rather than install it using Composer. Is that correct ?? If so, you will need to include (require) the relevant files in your mail script:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '/gfdev/resources/PHPMailer-6.0/src/Exception.php';
require '/gfdev/resources/PHPMailer-6.0/src/PHPMailer.php';
require '/gfdev/resources/PHPMailer-6.0/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions

try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('chris@example.com', 'Chris');
    $mail->addAddress('someone@example.net', 'Someone Else');     // Add a recipient
    $mail->addReplyTo('chris@example.com', 'Chris');

    //Content
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

Open in new window

Whilst your testing this, just create a script to send a basic email - take all of the POST / SESSION stuff out of the equation.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Chris,

I'll try at once :)
0
Peter KromanSales ExecutiveAuthor Commented:
Hi again,

I get this error:
2018-05-03 14:34:02 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Meddelelsen kunne ikke sendes. Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

with this code:
// Code that sends the content of the form to one email adress
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../resources/PHPMailer-6.0/src/Exception.php';
require '../resources/PHPMailer-6.0/src/PHPMailer.php';
require '../resources/PHPMailer-6.0/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions

try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'admin@genealogiskforum.dk';                 // SMTP username
    $mail->Password = '#myPassword"';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('admin@genealogiskforum.dk', 'Admin');
    $mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
    //$mail->addReplyTo('', '');

    //Content
    $mail->Subject = 'Meddelelse fra Gf Kontakt ';
    $mail->Body    = 'This is the HTML message body';

    $mail->send();
    echo 'Meddelelsen er sendt';
} catch (Exception $e) {
    echo 'Meddelelsen kunne ikke sendes. Mailer Error: ', $mail->ErrorInfo;
}

Open in new window


I have also tested port 465 and 993 - same result :)

But should I not set the right servers too - here is what they are in my mail system

Sk-rmbillede-2018-05-03-16.39.19.png
0
Chris StanyonWebDevCommented:
If you don't set a Host address it will default to localhost, which is the server the script is running on. If you need to send out through a specific server, then Yes - you should be setting a Host. Add a value to the Host property in your config and give that a go:

$mail->SMTPDebug = 2;                                 // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'asmtp.unoeuro,com';
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'admin@genealogiskforum.dk';                 // SMTP username
$mail->Password = '#myPassword"';

Open in new window

You might also want to set the reply address. Some servers may reject mail if it's not set:

$mail->setFrom('admin@genealogiskforum.dk', 'Admin');
$mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
$mail->addReplyTo('admin@genealogiskforum.dk', 'Admin');

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
Right :)

Now I get this message. How do I get around that about automated mails?
I know that this can work because I have it working with these exact credentials on a similar page built from RapidWeaver .... (https://genealogiskforum.dk/kontakt/)

2018-05-03 15:04:00 SERVER -> CLIENT: 220 asmtp.unoeuro.com - Ready. No automated mails or mass-mailing activities allowed.
2018-05-03 15:04:00 CLIENT -> SERVER: EHLO kroweb.dk
2018-05-03 15:04:00 SERVER -> CLIENT: 250-asmtp.unoeuro.com250-PIPELINING250-SIZE250-ETRN250-STARTTLS250-AUTH PLAIN LOGIN CRAM-MD5250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2018-05-03 15:04:00 CLIENT -> SERVER: STARTTLS
2018-05-03 15:04:00 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2018-05-03 15:04:00 CLIENT -> SERVER: EHLO kroweb.dk
2018-05-03 15:04:00 SERVER -> CLIENT: 250-asmtp.unoeuro.com250-PIPELINING250-SIZE250-ETRN250-AUTH PLAIN LOGIN CRAM-MD5250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2018-05-03 15:04:00 CLIENT -> SERVER: AUTH CRAM-MD5
2018-05-03 15:04:00 SERVER -> CLIENT: 334 PDUyNDE4NTE1MzY2OTk4NDguMTUyNTM1OTg0MEBhc210cC51bm9ldXJvLmNvbT4=
2018-05-03 15:04:00 CLIENT -> SERVER: YWRtaW5AZ2VuZWFsb2dpc2tmb3J1bS5kayBhYTkxMDY1MDYyYzExMmE2ODFmZWRiYWUzY2QxMDNkMg==
2018-05-03 15:04:00 SERVER -> CLIENT: 235 2.7.0 Authentication successful
2018-05-03 15:04:00 CLIENT -> SERVER: MAIL FROM:<admin@genealogiskforum.dk>
2018-05-03 15:04:00 SERVER -> CLIENT: 250 2.1.0 Ok
2018-05-03 15:04:00 CLIENT -> SERVER: RCPT TO:<peter_kroman@genealogiskforum.dk>
2018-05-03 15:04:00 SERVER -> CLIENT: 554 5.7.1 <linux159.unoeuro.com[94.231.103.180]>: Client host rejected: Relay from servers and automated mails are not allowed
2018-05-03 15:04:00 SMTP ERROR: RCPT TO command failed: 554 5.7.1 <linux159.unoeuro.com[94.231.103.180]>: Client host rejected: Relay from servers and automated mails are not allowed
2018-05-03 15:04:00 CLIENT -> SERVER: QUIT
2018-05-03 15:04:10 SERVER -> CLIENT: 221 2.0.0 Bye
SMTP Error: The following recipients failed: peter_kroman@genealogiskforum.dk: <linux159.unoeuro.com[94.231.103.180]>: Client host rejected: Relay from servers and automated mails are not allowed
Meddelelsen kunne ikke sendes. Mailer Error: SMTP Error: The following recipients failed: peter_kroman@genealogiskforum.dk: : Client host rejected: Relay from servers and automated mails are not allowed
0
Chris StanyonWebDevCommented:
OK. Looks like you'll need to speak to your hosting company to see if there's any specific config that you need to provide. These problems are nearly always down to the way the server is configured, so not sure what else I can suggest. The code I've provided works as-is on my server, so I know it's correct (for my server!)
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Chris,

I am working on it, and I will be back to morrow :)

Take care :)
0
Peter KromanSales ExecutiveAuthor Commented:
I am back again - and a little less frustrated than yesterday - sorry for that :)

Well - I have now got it to send an email logging in to another of my mail accounts, which I can live with :)  

But I still have a few issues. The code now looks like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start the session
session_start();

$navn = $_POST['navn'];
$email = $_POST['e-mail'];
$emne = $_POST['emne'];
$besked = $_POST['besked'];

// Prevent direct access to the script
if (!isset($_POST['navn'])) die("Access Denied!");

// Code that sends the content of the form to one email adress
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../resources/PHPMailer-6.0/src/Exception.php';
require '../resources/PHPMailer-6.0/src/PHPMailer.php';
require '../resources/PHPMailer-6.0/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions


try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'peter_kroman@live.dk';                 // SMTP username
    $mail->Password = 'myPassword?';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('peter_kroman@live.dk', 'Admin');
    $mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
    
    $mail->addReplyTo($email, $navn);

    //Content
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = $besked;





    $mail->send();
    echo 'Meddelelsen er sendt';
} catch (Exception $e) {
    echo 'Meddelelsen kunne ikke sendes. Mailer Error: ', $mail->ErrorInfo;
}

        if ($mail->send()): 


        $response = array(
            "success" => 1,
            "message" => "Din-email er sendt"
            );

        else: 

            $response = array(
                "success" => 0,
                "message" => "Noget gik galt. Prøv igen."
                );  

        endif;  



  // Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
//header('Location: ' . $_SERVER['HTTP_REFERER']);

?>

Open in new window



The remaining issues are:
1. The charset in the e-mail is not UTF-8. How to set that right?
2. it goes very slowly - I think it might be the $mail->ErrorInfo that takes time?? How do I fix that?
3. I need the e-mail to reflect all the four lines in the form - on four lines in the e-mail. How do I set that up?
4. I need to return to the form after sending the e-mail, and not stay on the "action-file" page. The line: header('Location: ' . $_SERVER['HTTP_REFERER']); gives an error so I have commented that out for now. How do I set this up?
5. The form should reset after submitting, which it is not doing now. How do I fix that?
0
Chris StanyonWebDevCommented:
Hey Peter. Glad you got it sending. Looks like your original mail server didn't allow the sending.

OK. To set the Character Set to UTF-8, you just set the property:

$mail->CharSet = 'UTF-8';

Regarding going slowly, it's not likely to be the ErrorInfo as that only gets called if there's an actual error. You are however sending the email twice in your code, which may slow things down. Each time you call $mail->Send(), the message get' sent, so you should only call that once. Sending an email won't be immediate as it has to connect to a remote server, so there is likely to be a slight delay.

You can generate whatever message you like, so if you want all four lines in the form, then build your message like so:

$_POST['navn'] . PHP_EOL . $_POST['e-mail'] . PHP_EOL . $_POST['emne'] . PHP_EOL . $_POST['besked'] . PHP_EOL;

This will concatenate your 4 fields into 4 new lines (PHP_EOL is the code for a new line);

The reason your header() method gives an error is because you have already output some data (echo 'Meddelelsen er sendt';). Header calls will only work if you haven't already output some info.

Resetting the form can be done a couple of ways, depending on how you're calling the mailing script. If you're calling it like a normal form (POST) then it should reset when the script redirects back to it. If you're calling it using an AJAX call (probably the nicest way to do it), then you can call the reset() method on the form:

$('#myForm').trigger("reset");

Have a look at the following:

try {

    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'peter_kroman@live.dk';                 // SMTP username
    $mail->Password = 'myPassword?';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->CharSet = 'UTF-8';

    //Recipients
    $mail->setFrom('peter_kroman@live.dk', 'Admin');
    $mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
    $mail->addReplyTo($_POST['e-mail'], $_POST['navn']);

    //Content
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = $_POST['navn'] . PHP_EOL . $_POST['e-mail'] . PHP_EOL . $_POST['emne'] . PHP_EOL . $_POST['besked'] . PHP_EOL;

    $mail->send();

    $response = array(
        "success" => 1,
        "message" => "Din-email er sendt"
    );

} catch (Exception $e) {

    $response = array(
        "success" => 0,
        "message" => "Noget gik galt. Prøv igen."
    );  

}

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// And send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

Open in new window

0
Chris StanyonWebDevCommented:
One thing I missed in my previous comment. When i said the header function would error if you output anything, I referred to the echo 'Meddelelsen er sendt' line. Because you have the debug mode switched on, that will also output a lot of information, breaking the header() call.

If you need to use the header() call, then you should either turn off the debug (suggested for production):

$mail->SMTPDebug = 0;

Or you can turn on Output buffering in your script, and then flush it before header call.
0
Peter KromanSales ExecutiveAuthor Commented:
Yes - the line $mail->SMTPDebug = 0; returns now only the message 'Meddelelsen er sendt' :)
0
Peter KromanSales ExecutiveAuthor Commented:
Hey - I did'nt see your first post above.

I am going to work at once :)
0
Chris StanyonWebDevCommented:
Cool. That will still break your header call though because you've output data BEFORE calling header (i.e you've echoed something out). If you want you header() call to work, then you'll need to make sure nothing is echoed out before calling it.
0
Peter KromanSales ExecutiveAuthor Commented:
Everything seems to be working now :) The reset of the form came by it self as the other things got working right

The lase little issue I have is that I would like to be able to CSS control the output to the e-mail. The mail content is now built like this:
//Content
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = 'Navn:  ' . $_POST['navn'] . PHP_EOL . 'e-mail:  ' . $_POST['e-mail'] . PHP_EOL . 'Emne:  ' . $_POST['emne'] . PHP_EOL . 'Besked:  ' . $_POST['besked'] . PHP_EOL;

Open in new window

0
Chris StanyonWebDevCommented:
OK Peter,

If you want to control the CSS, then you'll need to format your email to be HTML. CSS in HTML emails is only really basically supported so don't expect great things. You would then need to setup your message body to be a complete HTML document, including the CSS. You can either do this 'inline' or with an include. We should also include a non-html version of your email in the AltBody property for those that don't have HTML email clients:

    //Content
    $htmlMessage = <<< EOT
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Chris Stanyon</title>
        <style type="text/css">
            body { font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
            table { border: 1px solid green; }
            td { padding: 10px; }
        </style>    
    </head>
    <body>

        <table>
            <tr>
                <td>Name:</td>
                <td>{$_POST['navn']}</td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><a href="{$_POST['e-mail']}">{$_POST['e-mail']}</a></td>
            </tr>
            <tr>
                <td>Emne:</td>
                <td>{$_POST['emne']}</td>
            </tr>
            <tr>
                <td>Beksed:</td>
                <td>{$_POST['besked']}</td>
            </tr>
        </table>

    </body>
</html>
EOT;

    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = $htmlMessage;
    $mail->AltBody = 'Navn:  ' . $_POST['navn'] . PHP_EOL . 'e-mail:  ' . $_POST['e-mail'] . PHP_EOL . 'Emne:  ' . $_POST['emne'] . PHP_EOL . 'Besked:  ' . $_POST['besked'] . PHP_EOL;
    $mail->send();

Open in new window

0
Peter KromanSales ExecutiveAuthor Commented:
OK. Thanks Chris,

I will work with this :)
0
Peter KromanSales ExecutiveAuthor Commented:
I think I'll keep it as is. The hTML stuff is not working :)

But is there no way I can get another font in the e-mail body? That's the only thing i need. Right now it is the lousiest of all fonts that is displayed in the e-mail :) :)

Sk-rmbillede-2018-05-04-15.45.59.png
0
Chris StanyonWebDevCommented:
Hey Peter. No - if you want fonts (or any formatting), then you have to go with HTML. Plain text is exactly what it sounds like - plain text!

What do mean specifically when you say 'it's not working'. I've tested the code I sent and it worked as it should. Post up your code and I'll take a look
0
Peter KromanSales ExecutiveAuthor Commented:
It returns a success message, but is is not sending any mail with the HTML stuff.

The phpmailer code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start the session
session_start();

$navn = $_POST['navn'];
$email = $_POST['e-mail'];
$emne = $_POST['emne'];
$besked = $_POST['besked'];

// Prevent direct access to the script
if (!isset($_POST['navn'])) die("Access Denied!");

// Code that sends the content of the form to one email adress
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../resources/PHPMailer-6.0/src/Exception.php';
require '../resources/PHPMailer-6.0/src/PHPMailer.php';
require '../resources/PHPMailer-6.0/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions


try {
    $mail->CharSet = 'UTF-8';
    //Server settings
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'peter_kroman@live.dk';                 // SMTP username
    $mail->Password = 'mYpassword';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('peter_kroman@live.dk', 'Admin');
    $mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
    
    $mail->addReplyTo($email, $navn);

    // Send the user on his way
    header('Location: ' . $_SERVER['HTTP_REFERER']);

    //Content
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    
    include('mail-body.php');
    
     //$mail->Body    = 'Navn:    ' . $_POST['navn'] . PHP_EOL . 'e-mail:  ' . $_POST['e-mail'] . PHP_EOL . 'Emne:    ' . $_POST['emne'] . PHP_EOL . 'Besked:  ' . $_POST['besked'] . PHP_EOL;

  
     //$mail->send();

     $response = array(
            "success" => 1,
            "message" => "Din-email er sendt"
            );
           

       } catch (Exception $e) {

        $response = array(
                "success" => 0,
                "message" => "Noget gik galt. Prøv igen."
                );  
 
  }


  // Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);




?>

Open in new window


The mail-body.php code (your code)
    //Content
    $htmlMessage = <<< EOT
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Chris Stanyon</title>
        <style type="text/css">
            body { font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
            table { border: 1px solid green; }
            td { padding: 10px; }
        </style>    
    </head>
    <body>

        <table>
            <tr>
                <td>Name:</td>
                <td>{$_POST['navn']}</td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><a href="{$_POST['e-mail']}">{$_POST['e-mail']}</a></td>
            </tr>
            <tr>
                <td>Emne:</td>
                <td>{$_POST['emne']}</td>
            </tr>
            <tr>
                <td>Beksed:</td>
                <td>{$_POST['besked']}</td>
            </tr>
        </table>

    </body>
</html>
EOT;

    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = $htmlMessage;
    $mail->AltBody = 'Navn:  ' . $_POST['navn'] . PHP_EOL . 'e-mail:  ' . $_POST['e-mail'] . PHP_EOL . 'Emne:  ' . $_POST['emne'] . PHP_EOL . 'Besked:  ' . $_POST['besked'] . PHP_EOL;
    $mail->send();

Open in new window

0
Chris StanyonWebDevCommented:
Hey Peter,

The code I posted was an example of generating the HTML Email 'inline'. You've gone and dropped it, along with part of your mail script into an external file and tried including that. It doesn't work like that!

You've also moved the header() call into the middle of your script for some reason.

What your code should look like is this:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Prevent direct access to the script
if (!isset($_POST['navn'])) die("Access Denied!");

// Start the session
session_start();

// Code that sends the content of the form to one email adress
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../resources/PHPMailer-6.0/src/Exception.php';
require '../resources/PHPMailer-6.0/src/PHPMailer.php';
require '../resources/PHPMailer-6.0/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions

try {
    //Server settings
    $mail->SMTPDebug = 0;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.live.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'peter_kroman@live.dk';                 // SMTP username
    $mail->Password = 'mYpassword';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to
    $mail->CharSet = 'UTF-8';
    $mail->isHTML(true);

    //Recipients
    $mail->setFrom('peter_kroman@live.dk', 'Admin');
    $mail->addAddress('peter_kroman@genealogiskforum.dk', 'Peter Gf');     // Add a recipient
    $mail->addReplyTo($_POST['e-mail'], $_POST['navn']);

    //Content
    $htmlMessage = <<< EOT
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style type="text/css">
            body { font-family: Arial, Helvetica, sans-serif; font-size: 12px; }
            table { border: 1px solid green; }
            td { padding: 10px; }
        </style>    
    </head>
    <body>
        <table>
            <tr>
                <td>Name:</td>
                <td>{$_POST['navn']}</td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><a href="{$_POST['e-mail']}">{$_POST['e-mail']}</a></td>
            </tr>
            <tr>
                <td>Emne:</td>
                <td>{$_POST['emne']}</td>
            </tr>
            <tr>
                <td>Beksed:</td>
                <td>{$_POST['besked']}</td>
            </tr>
        </table>
    </body>
</html>
EOT;

    $mail->Subject = 'genealogiskforum.dk fra Kontakt';
    $mail->Body    = $htmlMessage;
    $mail->AltBody = 'Navn:  ' . $_POST['navn'] . PHP_EOL . 'e-mail:  ' . $_POST['e-mail'] . PHP_EOL . 'Emne:  ' . $_POST['emne'] . PHP_EOL . 'Besked:  ' . $_POST['besked'] . PHP_EOL;
    
    $mail->send();

    $response = array(
        "success" => 1,
        "message" => "Din-email er sendt"
    );

} catch (Exception $e) {

    $response = array(
        "success" => 0,
        "message" => "Noget gik galt. Prøv igen."
    );  
 
}

// Let's push the response to the SESSION
$_SESSION['response'] = json_encode($response);

// Send the user on his way
header('Location: ' . $_SERVER['HTTP_REFERER']);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Peter KromanSales ExecutiveAuthor Commented:
Cheers :)

Now it is working nicely.

Thanks a lot Chris.
0
Chris StanyonWebDevCommented:
No worries Peter :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.