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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.