wp_mail attachment not working

Hello I am trying to send mail with some attachment using with wordpress wp_mail functionality but I am not getting attachment in my mailbox.

Can you please check my bellow code and guide me where I am wrong. You can see I am seeding image in attachment.

<?php
    $to  = '[email protected]';
    $subject="WordPress wp_mail";
    $message="
    <html>
    <body>
        <table rules="all" style="border-color: #666;" cellpadding="10">
          <tr>Hello WordPress</tr>
        </table>          
    </body>
    </html>
    ";

    $attachments = array( 'http://sitename/project/wp-content/plugins/my-plugin/uploads/sample_photo_01.jpg' );
    //$attachments = array(WP_CONTENT_DIR  . '/uploads/'.$_FILES["myfile"]["name"]);
    $headers[] = 'MIME-Version: 1.0' . "\r\n";
    $headers[] = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers[] = 'From: '.get_option( 'blogname' ).' <'.get_option( 'admin_email' ).'>';

    wp_mail( $to, $subject, $message, $headers, $attachments );
?>

Thanks.

3 Answers
3

Attachments should always use the absolute filesystem path.

Also to change the Content-Type of the email you should use the wp_mail_content_type filter.

<?php
function my_custom_email() {
    $to  = '[email protected]';
    $subject="WordPress wp_mail";
    $message="
    <html>
    <body>
        <table rules="all" style="border-color: #666;" cellpadding="10">
          <tr>Hello WordPress</tr>
        </table>          
    </body>
    </html>
    ";

    $attachments = array(  WP_PLUGIN_DIR . '/my-plugin/uploads/sample_photo_01.jpg' );
    $headers[] = 'From: '.get_option( 'blogname' ).' <'.get_option( 'admin_email' ).'>';
    add_filter( 'wp_mail_content_type', 'my_custom_email_content_type' );
    return wp_mail( $to, $subject, $message, $headers, $attachments );
}

function my_custom_email_content_type() {
    return 'text/html';
}

I have placed the entire code in a function so that the wp_mail_content_type filter applies only to this email.

Sources:
http://codex.wordpress.org/Function_Reference/wp_mail
http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type

Leave a Comment