Search code examples
phpemailphpmailerhtml-email

PHP: How to modify working email script to run on own server (PHP mail server setup on LAMP server)


I am using lines like the below to send emails after submitting a form on my website.
So far everyhing works as intended.

Now I would like to set up my own server and would like to avoid setting up an email client on this server.
Can someone tell me what I have to add here to set this up to use a mailing server ?
Does this work using IP addresses or do I need an extra PHP file for this kind of set up ?

Note: My emails will only contain text and some basic HTML, no attachments.

I am pretty new to PHP and was hoping to get some help in getting started with this here.

My PHP (shortened):

// get submitted form data
$postData = $_POST;
// retrieve some post data to include in email

unset($postData);

// prepare email
$to = '[email protected]';   
$subject = 'Some text';

$emailBody = '<html><body>Some HTML text</body></html>';    
$headers = 'From: Someone <[email protected]>' . PHP_EOL .
    'Cc: [email protected] <[email protected]>' . PHP_EOL .
    'Reply-To: [email protected] <[email protected]>' . PHP_EOL .
    'X-Mailer: PHP/' . phpversion();                                

// set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";

// send email
$mail = mail($to, $subject, $emailBody, $headers);

if($mail) {
    header('Location: support.php?status=emailSent');
}

Many thanks in advance, Tom


Solution

  • Open your php.ini file an look for "[mail function]". You can specify your SMTP server/port/credentials there.

    [mail function]    
    SMTP = smtp.example.com
    smtp_port = 25
    username = [email protected]
    password = yourmailpassord
    sendmail_from = [email protected]
    

    Here you can set it up like your email client on whatever machine you have email set up.