我在做CS1010(Programming Methodology)的Tutor,其中一個任務是給學生作業判分,然後把判分的結果發給學生。
學生作業在我電腦裏面folder的結構是:題號->學生學號->題目;其中題目爲C code,有時候有其它的Tutor用Word判分之後會把結果發給我。
爲了保護學生隱私,我需要分別給每個學生髮送他的成績,附上他的批改過的作業作爲附件。於是,我可以用電腦來做這個重複而且麻煩的事情。
這裏用的是PHP,以及它的Pear組件中的Pear_mail (用來發送email),和pear_mime(用來給email加入附件)。學生的email就是學生學號@學校網址。
code見下(這裏居然不能用PHP後綴作爲附件!應該是因爲怕上傳上去自動執行PHP吧~)。我覺得這是一次很好的Programming Practice——把一些編程技巧拿來解決實際問題。
<?php
// basic email settings
require_once "Mail.php";
require_once "Mail/mime.php";
$params = array(
'host' => "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
"<p>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.</p></br><p>Regards, </p> <p>Your Name</p>";
// 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";
}
}
?>