2026年7月23日
2026年7月23日
WordPressのwp_mailでメール送信をカスタマイズする方法
はじめに
「WordPressのメール送信元をnoreply@example.comに変更したい」「HTMLメールでお知らせを送りたい」「Gmailのアプリパスワード経由でメールを送信したい」——wp_mail()のフックとPHPMailerのカスタマイズで柔軟なメール設定が実現できます。
症状・原因
WordPressはデフォルトでwordpress@ドメインからsendmailまたはmail()関数でメールを送信します。サーバー設定によっては迷惑メールに分類されたりメール自体が届かないことがあります。SMTPで送信することで信頼性が大幅に向上します。
解決手順
ステップ1:送信元メールアドレスと名前を変更する
// functions.php: 送信元をカスタマイズ
// 送信元メールアドレスを変更
add_filter( 'wp_mail_from', function( string $email ): string {
return 'noreply@example.com';
} );
// 送信者名を変更
add_filter( 'wp_mail_from_name', function( string $name ): string {
return get_bloginfo( 'name' );
} );
// コンテンツタイプをHTMLに変更(全メールに適用)
add_filter( 'wp_mail_content_type', function(): string {
return 'text/html';
} );
ステップ2:HTMLメールを送信する
// HTMLメールを送信する関数
function send_html_email(
string $to,
string $subject,
string $message,
array $extra_headers = []
): bool {
// メール送信直前だけHTMLに変更
add_filter( 'wp_mail_content_type', fn() => 'text/html' );
$headers = array_merge(
[ 'Content-Type: text/html; charset=UTF-8' ],
$extra_headers
);
$html_message = sprintf( '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: -apple-system, sans-serif; font-size: 14px; color: #1d2327; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: #0073aa; color: #fff; padding: 20px; border-radius: 4px 4px 0 0; }
.body { background: #fff; padding: 20px; border: 1px solid #e0e0e0; }
.footer { background: #f0f0f1; padding: 12px 20px; font-size: 12px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header"><h2 style="margin:0">%s</h2></div>
<div class="body">%s</div>
<div class="footer">%s から送信</div>
</div>
</body>
</html>',
esc_html( $subject ),
wp_kses_post( $message ),
esc_html( get_bloginfo( 'name' ) )
);
$result = wp_mail( $to, $subject, $html_message, $headers );
// フィルターをリセット(他のメールに影響しないよう)
remove_filter( 'wp_mail_content_type', fn() => 'text/html' );
return $result;
}
// 使用例
send_html_email(
'user@example.com',
'会員登録ありがとうございます',
'<p>この度は会員登録ありがとうございます。</p><p><a href="https://example.com">サイトへ戻る</a></p>'
);
ステップ3:添付ファイル付きメールを送信する
// 添付ファイル付きのメール送信
function send_email_with_attachment(
string $to,
string $subject,
string $message,
int $attachment_id
): bool {
$file_path = get_attached_file( $attachment_id );
if ( ! $file_path || ! file_exists( $file_path ) ) {
return false;
}
return wp_mail(
$to,
$subject,
$message,
[ 'Content-Type: text/plain; charset=UTF-8' ],
[ $file_path ] // 添付ファイルのフルパスを配列で渡す
);
}
// 一時ファイルを添付する場合
function send_with_temp_attachment( string $to, string $subject ): bool {
// 一時ファイルを作成
$tmp_file = wp_tempnam( 'report' );
file_put_contents( $tmp_file, "日次レポート\n生成日: " . current_time( 'Y-m-d' ) );
$result = wp_mail(
$to,
$subject,
'レポートを添付しました。',
[],
[ $tmp_file ]
);
// 送信後に一時ファイルを削除
wp_delete_file( $tmp_file );
return $result;
}
ステップ4:PHPMailerでSMTP送信を設定する
// functions.php: SMTP設定(wp-config.phpに定数を定義)
add_action( 'phpmailer_init', function( PHPMailer\PHPMailer\PHPMailer $phpmailer ): void {
$phpmailer->isSMTP();
$phpmailer->Host = defined( 'SMTP_HOST' ) ? SMTP_HOST : '';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = defined( 'SMTP_PORT' ) ? (int) SMTP_PORT : 587;
$phpmailer->Username = defined( 'SMTP_USER' ) ? SMTP_USER : '';
$phpmailer->Password = defined( 'SMTP_PASS' ) ? SMTP_PASS : '';
$phpmailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
$phpmailer->CharSet = 'UTF-8';
$phpmailer->Encoding = 'base64';
} );
// wp-config.php に追加(ソースコードに認証情報を書かない)
// Gmail の場合: Google アカウント → セキュリティ → アプリパスワードを使用
// define( 'SMTP_HOST', 'smtp.gmail.com' );
// define( 'SMTP_PORT', 587 );
// define( 'SMTP_USER', 'your@gmail.com' );
// define( 'SMTP_PASS', 'xxxx xxxx xxxx xxxx' ); // 16桁のアプリパスワード
// SendGrid の場合
// define( 'SMTP_HOST', 'smtp.sendgrid.net' );
// define( 'SMTP_PORT', 587 );
// define( 'SMTP_USER', 'apikey' );
// define( 'SMTP_PASS', 'SG.xxxxxxxx' ); // SendGrid APIキー
ステップ5:メール送信エラーをデバッグする
// wp_mail_failed フックでエラーをキャッチ
add_action( 'wp_mail_failed', function( WP_Error $error ): void {
// エラーログに記録
error_log( 'wp_mail failed: ' . $error->get_error_message() );
error_log( 'Error data: ' . print_r( $error->get_error_data(), true ) );
// 管理者に通知(無限ループを防ぐため直接PHPMailerを使う)
$admin_email = get_option( 'admin_email' );
if ( $admin_email ) {
@mail(
$admin_email,
'WordPressメール送信エラー',
'エラー: ' . $error->get_error_message()
);
}
} );
// SMTPデバッグを有効化(開発環境のみ)
add_action( 'phpmailer_init', function( PHPMailer\PHPMailer\PHPMailer $phpmailer ): void {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$phpmailer->SMTPDebug = 2; // 0=off 1=client 2=server
$phpmailer->Debugoutput = function( string $str ): void {
error_log( 'SMTP Debug: ' . $str );
};
}
} );
// テスト送信関数
function test_wp_mail(): void {
$result = wp_mail(
get_option( 'admin_email' ),
'wp_mail テスト ' . current_time( 'Y-m-d H:i:s' ),
'このメールはwp_mailのテストです。'
);
error_log( 'wp_mail test result: ' . ( $result ? 'success' : 'failed' ) );
}
// WP-CLIから実行: wp eval 'test_wp_mail();'
注意事項
wp_mail_content_typeフィルターでグローバルにHTMLに変更すると、WordPressコアのテキストメール(パスワードリセットなど)もHTMLとして送られ崩れる場合があります。関数内でフィルターを追加して処理後に削除するパターンを推奨します。- Gmail SMTPのアプリパスワードには2段階認証の有効化が必要です。通常のパスワードでは認証できません。
SMTP_PASSなどの認証情報はソースコードに直接書かず、wp-config.phpの定数定義か環境変数で管理してください。
まとめ
wp_mailのカスタマイズは「wp_mail_from/wp_mail_from_nameフィルターで送信元変更→wp_mail()の第4引数でヘッダー指定・第5引数で添付ファイル→phpmailer_initフックでSMTP設定(Gmail/SendGrid)→wp_mail_failedフックでエラー検知→SMTPDebugでデバッグ」の流れで整備します。関連記事:WordPressのWooCommerceメールテンプレートをカスタマイズする方法、WordPressのCronジョブをwp_schedule_eventで設定する方法。