Send email to user when I publish a new post

Updated code for statuses as per @Fredrik’s answer as his is more accurate.


To trigger this when publishing, you could change your first if to

if ( $new_status === 'inherit' && $old_status === 'new' )

That way, your code should trigger only when you publish a post.

EDIT:

Some notes on your code.

if ( ! $post_type = get_post_type_object( $post->post_type ) )

this will do nothing, as it’s an assignment for a variable. It means, that you will get the current post type, and assign it to $post_type and it will always pass.

What I think you’re trying to achieve, is for this to work only for a specific post type. If that’s the case, change this line to:

if ( 'my_custom_post_type' !== get_post_type_object( $post->post_type ) )

where my_custom_post_type should be the post type for which you wish to send emails for.

For this line:

$newsletteremailall = $newsletteremailall->email; 

It’s a bad practice to overwrite the initial variable. Maybe name it $email instead of $newsletteremailall, because you may need it later, but you will no longer have access to it.