HEX
Server: nginx/1.16.1
System: Linux ecs-04358622 4.19.90-2107.6.0.0100.oe1.bclinux.x86_64 #1 SMP Wed Dec 1 19:59:44 CST 2021 x86_64
User: nginx (994)
PHP: 8.0.0
Disabled: NONE
Upload Files
File: /home/www/wp-content/plugins/wpjam-basic/extends/wpjam-smtp.php
<?php
/*
Name: SMTP 发信
URI: https://mp.weixin.qq.com/s/SbuvSL01hT3Jxp9doWZ8zg
Description: SMTP 发信可以让你使用第三方邮箱的 SMTP 服务来发送邮件。
Version: 2.0
*/
class WPJAM_SMTP extends WPJAM_Option_Model{
	public static function get_fields(){
		return [
			'smtp_setting'		=> ['title'=>'SMTP 设置',	'type'=>'fieldset',	'fields'=>[
				'host'	=> ['title'=>'SMTP地址',	'type'=>'text',		'class'=>'',	'value'=>'smtp.qq.com'],
				'user'	=> ['title'=>'邮箱账号',	'type'=>'email',	'class'=>''],
				'pass'	=> ['title'=>'邮箱密码',	'type'=>'password',	'class'=>''],
				'ssl'	=> ['title'=>'发送协议',	'type'=>'text',		'class'=>'',	'value'=>'ssl'],
				'port'	=> ['title'=>'SSL端口',	'type'=>'number',	'class'=>'',	'value'=>'465'],
			]],
			'mail_from_name'	=> ['title'=>'发送者姓名',	'type'=>'text',	'class'=>''],
			'reply_to_mail'		=> ['title'=>'回复地址',		'type'=>'email','class'=>'',	'description'=>'不填则用户回复使用SMTP设置中的邮箱账号']
		];
	}

	public static function get_form(){
		return [
			'submit_text'	=> '发送',
			'callback'		=> fn($data)=> wp_mail($data['to'], $data['subject'], $data['message']),
			'validate'		=> true,
			'fields'		=> [
				'to'		=> ['title'=>'收件人',	'type'=>'email',	'required'],
				'subject'	=> ['title'=>'主题',		'type'=>'text',		'required'],
				'message'	=> ['title'=>'内容',		'type'=>'textarea',	'required'],
			]
		];
	}

	public static function add_hooks(){
		if(array_all(['host', 'user', 'pass'], fn($k)=> self::get_setting($k))){
			add_action('phpmailer_init', function($phpmailer){
				$phpmailer->Mailer		= 'smtp';
				$phpmailer->SMTPAuth	= true;
				$phpmailer->SMTPSecure	= self::get_setting('ssl', 'ssl');
				$phpmailer->Host		= self::get_setting('host'); 
				$phpmailer->Port		= self::get_setting('port', '465');
				$phpmailer->Username	= self::get_setting('user');
				$phpmailer->Password	= self::get_setting('pass');

				($reply_to	= self::get_setting('reply_to_mail')) && $phpmailer->AddReplyTo($reply_to, self::get_setting('mail_from_name', ''));
			});

			add_filter('wp_mail_from', fn()=> self::get_setting('user'));

			($from_name = self::get_setting('mail_from_name')) && add_filter('wp_mail_from_name', fn()=> $from_name);
		}

		(wp_doing_ajax() || wpjam_is_json_request()) && add_action('wp_mail_failed', 'wpjam_send_json');
	}
}

wpjam_register_option('wpjam-smtp',	[
	'model'		=> 'WPJAM_SMTP',
	'title'		=> '发信设置',
	'menu_page'	=> [
		'parent'		=> 'wpjam-basic',
		'page_title'	=> 'SMTP 发信',
		'network'		=> false,
		'summary'		=> __FILE__,
		'function'		=> 'tab',
		'tabs'			=> [
			'smtp'	=> ['title'=>'发信设置',	'function'=>'option'],
			'send'	=> ['title'=>'发送测试',	'function'=>'form',	'form'=>['WPJAM_SMTP', 'get_form']]
		]
	]
]);