在自定义时间自动发送电子邮件

时间:2014-09-11 作者:LET ME

我想每天10:00发送一封自动电子邮件

我试过这个密码

$timeN = date(\'H:i\');
$timeS = date(\'10:00\');
if ($timeS == $timeN) {
    $to = get_option(\'admin_email\');
    $nfrom = "my site";
    $subject = "test";
    $body = " Hello";
    $headers = \'From: "\'. $nfrom .\'" <\' . $to . \'>\';
    wp_mail=$mail($to, $subject, $body, $headers);
}
如果我刷新页面,它就会工作。如果页面已刷新或打开10次,则会发送10条消息。我怎样才能修复它?

对不起,我不是程序员,英语说得不好。

2 个回复
SO网友:Porosh Ahammed

Creating a Scheduled Event

首先,我们将创建一个用于安排活动的函数。我的名为“mycronjob”,每天运行一次。所有这些代码都可以进入插件的主文件,在主功能之外:

// create a scheduled event (if it does not exist already)
function cronstarter_activation() {
    if( !wp_next_scheduled( \'mycronjob\' ) ) {  
       wp_schedule_event( time(), \'daily\', \'mycronjob\' );  
    }
}
// and make sure it\'s called whenever WordPress loads
add_action(\'wp\', \'cronstarter_activation\');

Adding your Repeat Function

这只是您希望定期运行的代码的占位符:

// here\'s the function we\'d like to call with our cron job
function my_repeat_function() {

    // do here what needs to be done automatically as per your schedule
    // in this example we\'re sending an email

    // components for our email
    $recepients = \'[email protected]\';
    $subject = \'Hello from your Cron Job\';
    $message = \'This is a test mail sent by WordPress automatically as per your schedule.\';

    // let\'s send it 
    mail($recepients, $subject, $message);
}

// hook that function onto our scheduled event:
add_action (\'mycronjob\', \'my_repeat_function\'); 

After all that if you face some problem with specific time then you can check this answer Here

SO网友:T.Todua

您应该像这样插入验证器,这样它一天只能发送1封邮件:

$timeN = date(\'H:i\');
$timeS = date(\'10:00\');
if ($timeS == $timeN) 
{
    if (get_option(\'last_mail_sent_time\')!= date(\'d\'))
    {
     //your codes here


     //then
     update_option(\'last_mail_sent_time\', date(\'d\'));
    }
}

结束