Jump to content

Recommended Posts

Hi

I am trying to send email through php as html template. Below code, if I put the headers it will get the custom error message that the email is not sent. If I remove the headers it will send the email but the email will be not formatted as html and it will send the whole template.php as a text.

        $to = $myusername;
   		$subject = "OTP - RESET PASSWORD";
 
 	        $headers = array(
    		'MIME-Version' => '1.0',
    		'Content-type' => 'text/html;charset=UTF-8',
    		'From' => '[email protected]',
    		'Reply-To' => '[email protected]'
   		);

		//$message = "hi!";
  
   	     	ob_start();
   	     	include("mail-template.php");
   		$message = ob_get_contents();
   		ob_end_clean();
 
   		$sent = mail($to, $subject, $message);
 
   		if(!$sent){
      			echo "Error: Message not sent. Please try again";
   		}else{
      			echo "Message was sent successfully";
   		}

 

Link to comment
https://forums.phpfreaks.com/topic/327499-send-email-in-php/
Share on other sites

23 hours ago, maxxd said:

Highly recommend switching to a library like PHPMailer or SwiftMailer - they're both easier to use and more reliable than php's native mail function.

 

Agree strongly with this advice.  I would also suggest looking at Symfony Mailer.

  • 2 weeks later...

First of all, I think you should follow the above recommendations about using a library like Symfony Mailer, PHPMailer or better using a service as Sendgrid or Resend

Regarding your concern, may I ask which version of PHP you're using? Since PHP 7.2, the mail() function accepts headers as an array—before that, it only accepted strings.

Looking at example #5 in the documentation, you can see that they convert the array of headers into a string using the implode() function.

Something like this:

$headers = array( 'MIME-Version' => '1.0', 'Content-type' => 'text/html;charset=UTF-8', 'From' => '[email protected]', 'Reply-To' => '[email protected]' );

$sent = mail($to, $subject, $message, implode("\r\n", $headers));

 

 

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.