我在做CS1010(Programming Methodology)的Tutor,其中一个任务是给学生作业判分,然后把判分的结果发给学生。
学生作业在我电脑里面folder的结构是:题号->学生学号->题目;其中题目为C code,有时候有其它的Tutor用Word判分之后会把结果发给我。
为了保护学生隐私,我需要分别给每个学生发送他的成绩,附上他的批改过的作业作为附件。于是,我可以用电脑来做这个重复而且麻烦的事情。
这里用的是PHP,以及它的Pear组件中的Pear_mail (用来发送email),和pear_mime(用来给email加入附件)。学生的email就是学生学号@学校网址。
code见下(这里居然不能用PHP后缀作为附件!应该是因为怕上传上去自动执行PHP吧~)。我觉得这是一次很好的Programming Practice——把一些编程技巧拿来解决实际问题。
"ssl://smtp.gmail.com", 'port' => "465", 'auth' => true, 'username' => "[email protected]", // CONFIG your username comes here 'password' => "Your Password", // CONFIG and your password ); $from = "[email protected]"; // CONFIG your email address $cc = "[email protected]"; // CONFIG the cc address -- put your address so that you can confirm that the email has been sent successfully $subject = "[CS1010] PE Mark"; $body = // CONFIG: the message you want to pass to your student, it's in the HTML format "Please Check the attachment(the word file) for your PE1 Mark. I didn't mark your PE but the graders are following the same scheme. If you have any problem with it, please email me.
Regards,
Your Name
"; // Generate the location array $markLoc = "../PE_DG4"; // CONFIG: the file location of the folder storing ex1, ex2, ... $regEx = "/^ex\\d$/"; $regMatrix = "/^[au]\\d+$/"; $regWord = "/\\.docx$/"; $regCProg = "/\\.c$/"; // location str: $loc = array(); $fileNameArr = array($markLoc); foreach(scandir($markLoc) as $exName){ if(!preg_match($regEx,$exName)) continue; array_push($fileNameArr,$exName); foreach(scandir(implode("/",$fileNameArr)) as $matrixNum){ if(!preg_match($regMatrix,$matrixNum)) continue; if(!array_key_exists($matrixNum,$loc)) $loc[$matrixNum] = array(); array_push($fileNameArr,$matrixNum); foreach(scandir(implode("/",$fileNameArr)) as $file){ if(preg_match($regWord,$file)){ array_push($fileNameArr,$file); $loc[$matrixNum][] = implode("/",$fileNameArr); array_pop($fileNameArr); } else if(preg_match($regCProg,$file)){ array_push($fileNameArr,$file); $loc[$matrixNum][] = implode("/",$fileNameArr); array_pop($fileNameArr); } } array_pop($fileNameArr); } array_pop($fileNameArr); } // then send out emails to each specific student foreach($loc as $matrix => $files){ $message = new Mail_mime(); $message->setHTMLBody($body); // add in attachment here foreach($files as $file){ $message->addAttachment($file); } $to = $matrix."@nus.edu.sg"; $headers = array( 'From' => $from, 'Reply-to' => $from, 'To' => $to, 'Cc' => $cc, 'Subject' => $subject, ); $msgContent = $message->get(); $msgHeader = $message->headers($headers); $smtp = Mail::factory('smtp',$params); $mail = $smtp->send($to.",".$cc,$msgHeader,$msgContent); if(PEAR::isError($mail)){ echo "Error: ".$mail->getMessage()."\n"; } else{ echo "Message Sent Successfully to: $to\n"; } } ?>