WordPress   

Send emails without any plugin using wp_mail function in WordPress

In this article, we will create a small code snippet to send emails using the wp_mail function. We will use static values to keep this code snippet short and easy to understand. you can hook up custom form values and validations functions with it to create a full custom contact form. With proper customizations and validations, wp_mail function can be used to send complex survey form data with great ease.

Simple HTML emails

The following example is for sending simple HTML emails using wp_mail function in WordPress.

//Dummy Data -> update this with dyanmic form values
$first_name = 'John'; 
$last_name = 'Doe'; 
$email = 'johndoe@example.com'; 

$to = 'admin@example.com'; //Admin email ID to receive email notifications
$subject = "New Contact Form Submission";
$message = "Submission Data is given below.<br><br>";
$message .= "<strong>First Name - </strong>".$first_name."<br><br>";
$message .= "<strong>Last Name - </strong>".$last_name."<br><br>";
$message .= "<strong>Email - </strong>".$email."<br><br>";
$headers = array('Content-Type: text/html; charset=UTF-8','From: Website Name <wordpress@example.com>', 'Reply-To: ' . $email);
$mailsent = wp_mail( $to, $subject, $message, $headers);
if($mailsent){
    echo "Success";
}
else{
    echo "Failed";
}

Send emails with file attachments

The following code snippet can be used for sending emails with file attachments.

//Dummy Data -> update this with dyanmic form values
$first_name = 'John'; 
$last_name = 'Doe'; 
$email = 'johndoe@example.com'; 

$to = 'admin@example.com'; //Admin email ID to receive email notifications
$subject = "New Contact Form Submission";
$message = "Submission information and file attachment is given below.<br><br>";
$message .= "<strong>First Name - </strong>".$first_name."<br><br>";
$message .= "<strong>Last Name - </strong>".$last_name."<br><br>";
$message .= "<strong>Email - </strong>".$email."<br><br>";
$attachments = array(WP_CONTENT_DIR."/files/AMo.png");
$headers = array('Content-Type: text/html; charset=UTF-8','From: Website Name <wordpress@example.com>', 'Reply-To: ' . $email);
$mailsent = wp_mail( $to, $subject, $message, $headers,$attachments);
if($mailsent){
    echo "Success";
}
else{
    echo "Failed";
}
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us