How to use wp_mail in wordpress
wp_mail
is a WordPress function that allows you to send emails from your WordPress site. Here's a step-by-step guide on how to use it:
Basic Usage
The basic syntax for using wp_mail
is:
wp_mail( $to, $subject, $message, $headers = '', $attachments = array() );
Here:
$to
: The recipient's email address.$subject
: The subject of the email.$message
: The body of the email.$headers
: Optional headers for the email (e.g., "From", "Reply-To", etc.).$attachments
: Optional array of file paths or URLs to attach to the email.
Example
Here's an example of how to use wp_mail
to send a simple email:
wp_mail( '[email protected]', 'Hello from WordPress', 'This is a test email from WordPress.' );
This will send an email to [email protected]
with the subject "Hello from WordPress" and the body "This is a test email from WordPress."
Advanced Usage
You can also use wp_mail
to send more complex emails by specifying additional parameters. Here are some examples:
-
Adding headers: You can add custom headers to the email using the
$headers
parameter. For example:$headers = array( 'From' => 'Your Name <[email protected]>', 'Reply-To' => '[email protected]', 'Content-Type' => 'text/html; charset=UTF-8' ); wp_mail( '[email protected]', 'Hello from WordPress', 'This is a test email from WordPress.', $headers );
-
Adding attachments: You can add attachments to the email using the
$attachments
parameter. For example:$attachments = array( WP_CONTENT_DIR. '/uploads/file1.txt', WP_CONTENT_DIR. '/uploads/file2.pdf' ); wp_mail( '[email protected]', 'Hello from WordPress', 'This is a test email from WordPress.', '', $attachments );
-
Using HTML content: You can use HTML content in the email body by setting the
Content-Type
header totext/html
. For example:$message = '<p>This is a test email from WordPress.</p>'; $headers = array( 'Content-Type' => 'text/html; charset=UTF-8' ); wp_mail( '[email protected]', 'Hello from WordPress', $message, $headers );
Tips and Tricks
-
Make sure to use a valid email address for the recipient.
-
Use a valid subject and body for the email.
-
Use the
wp_mail
function in a WordPress context (e.g., in a plugin or theme file) to ensure that the email is sent correctly. -
You can use the
wp_mail
function to send emails to multiple recipients by separating their email addresses with commas. -
You can use the
wp_mail
function to send emails with attachments by specifying the file paths or URLs in the$attachments
parameter.