Halloween Sale 15% off Ends in See the plans
PHP

Skip Oversized Email Attachments

Removes attachments that would make an email larger than your mail server accepts and notes it in the message, so the email still arrives instead of bouncing.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_attachment_limit_mb = 15;

add_filter( 'wp_mail', function ( $atts ) use ( $wpide_attachment_limit_mb ) {
    if ( empty( $atts['attachments'] ) ) {
        return $atts;
    }

    $files   = is_array( $atts['attachments'] ) ? $atts['attachments'] : explode( "\n", str_replace( "\r\n", "\n", (string) $atts['attachments'] ) );
    $budget  = $wpide_attachment_limit_mb * MB_IN_BYTES;
    $kept    = array();
    $dropped = array();
    $used    = 0;

    foreach ( $files as $key => $file ) {
        $size = is_readable( $file ) ? (int) ceil( filesize( $file ) * 1.37 ) : 0;
        if ( $used + $size > $budget ) {
            $dropped[] = basename( $file );
            continue;
        }
        $used        += $size;
        $kept[ $key ] = $file;
    }

    if ( $dropped ) {
        $atts['attachments'] = $kept;
        $atts['message']    .= "\n\n(" . count( $dropped ) . ' attachment(s) were too large to send: ' . implode( ', ', $dropped ) . ')';
    }

    return $atts;
}, 40 );

Notes

Set the limit a little below your provider's maximum (often 10 to 25 MB); base64 encoding makes attachments about a third larger, which the snippet accounts for.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.