Optimise mail sending process of phpmailer - optimization

I am trying to send mails using phpmailer and code is working fine. However when I see the CPU usage history in task manager I could see it is fluctuating rapidly between 0% to 100%. And RAM usage is constant around 4.65GB of 6GB.
I was able to send 500 emails in 15 minutes or so and I feel its bit slow because my CPU usage is fluctuating a lot, may be I am wrong in my assumption.
Can anyone help me in optimizing max usage of my system and fasten the process?
Also I have created a column in table email_sent to check how many mails have been sent and avoid any duplication but the code is not updating the database and giving up! (so it is commented out below).
<?php
//this code sends mails in HTML format using emailids from database. It also sends attachment if needed.
error_reporting(E_ALL);
//error_reporting(E_STRICT);
ini_set("display_errors", "on");
ini_set('max_execution_time', 30000000); //300 seconds = 5 minutes
ini_set('memory_limit', '6500M'); //Maximum amount of memory a script may consume (128MB by default)
date_default_timezone_set('UTC');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents("contents.html");
//$body = preg_replace('/[\]/','',$body);
$body = preg_replace('/IDontKnowWTFThisFunctionIsdoing/','',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->Host = "ssl://smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "myemail#gmail.com"; // SMTP account username
$mail->Password = "password"; // SMTP account password
//$mail->SetFrom ('myemail#gmail.com', 'me');
$mail-> From = "myemail#gmail.com";
$mail->FromName = "me";
$mail->AddReplyTo ('myemail#gmail.com', 'me');
$mail->Subject = "Subject";
#MYSQL_CONNECT("localhost","root","");
#mysql_select_db("database");
$startnum1 = 501;
$endnum1 = 5000;
//$query = "SELECT emailid FROM test WHERE email_sent = 0 Limit $startnum1,$endnum1";
$query = "SELECT emailid FROM test Limit $startnum1,$endnum1";
$result = #MYSQL_QUERY($query);
echo "message sending in process";
while ($row = mysql_fetch_array ($result)) {
$mail->body = $body;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->IsHTML(true);
$mail->MsgHTML($body);
$mail->AddAddress($row["emailid"], $row["emailid"]);
//$mail->AddStringAttachment($row["emailid"], "contents.html");
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["emailid"]) . ') ' . $mail->ErrorInfo . '<br />';
} else {
//$query1 = "UPDATE test SET Email_Sent= 1 WHERE EmailID= emailid Limit $startnum1,$endnum1";
//$result1 = #MYSQL_QUERY($query1);
echo "Message sent to :" . $row["emailid"] . ' (' . str_replace("#", "#", $row["emailid"]) . ')<br />';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
//$mail->ClearAttachments();
}
[CPU history] (http://s3.postimg.org/v99ucpq6p/Capture.jpg)
[System information] (http://s3.postimg.org/3n72s16tt/Capture1.jpg)
?>

Related

Yii swift mailer not sending mail

I am using yii mail swiftmailer extension to send mail .when am using this mail extension along with ccaptcha validation in the same form the mail is not sending.when it has be used alone without captcha validation it is sending email.i need to send email using this extension along with the ccaptcha validation in yii.
for email:
$subjek="verifymail";
$from="sender#gmail.com";
$getEmail="to#gmail.com";
$message= new YiiMailMessage;
$message->subject=$subjek;
$message->from=$from;
$message->setBody($activationlink, 'text/html');
$message->addTo($getEmail);
Yii::app()->mail->send($message);
I think you are missing port and host information in your code,unless you didnt show your whole code,see example here
public function actionViewTest() {
// Render view and get content
// Notice the last argument being `true` on render()
$content = $this->render('viewTest', array(
'Test' => 'TestText 123',
), true);
// Plain text content
$plainTextContent = "This is my Plain Text Content for those with cheap emailclients ;-)\nThis is my second row of text";
// Get mailer
$SM = Yii::app()->swiftMailer;
// Get config
$mailHost = 'mail.example.com';
$mailPort = 25; // Optional
// New transport
$Transport = $SM->smtpTransport($mailHost, $mailPort);
// Mailer
$Mailer = $SM->mailer($Transport);
// New message
$Message = $SM
->newMessage('My subject')
->setFrom(array('from#example.com' => 'Example Name'))
->setTo(array('recipient#example.com' => 'Recipient Name'))
->addPart($content, 'text/html')
->setBody($plainTextContent);
// Send mail
$result = $Mailer->send($Message);
}
If your host is gmail,put the port to 587 or 465
$mail->Port = 587; or $mail->Port = 465;
here is a question almost similar to your question

How to make the website Ping ARR server and say I am going down?

I have successfully configured the ARR in Windows Azure environment, the web server instances are added to server farm.
Using Health Check option in server farm, instance that timed-out or not responding is made unhealthy.
My Question is
Instead of the ARR web farm (doing health check every 10 seconds) ping the website, is it possible or the web role itself ping back the ARR server and say I am going down ?
Is it possible to ping the ARR Server from web role and say I am going down? or this is there any best approach available.
Please suggest.
I wanted some extra notifications with our ARR setup and I put this PowerShell script together that runs once an hour and checks the health status and notify me via email when ever any hosting server was seen as unhealthy. We also use other outside resources that ping the web farm externally once an minute and alerts us when it can't be seen (Pingdom). I have a feeling you're looking for a little more than this but I hope it helps a little.
#----- First add a reference to the MWA dll ----#
$dll=[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Administration")
#----- Get the manager and config object ----#
$mgr = new-object Microsoft.Web.Administration.ServerManager
$conf = $mgr.GetApplicationHostConfiguration()
#----- Get the webFarms section ----#
$section = $conf.GetSection("webFarms")
$webFarms = $section.GetCollection()
#----- Define an array for html fragments ----#
$fragments=#()
#----- Check each webfarm ----#
foreach ($webFarm in $webFarms)
{
$Name= $webFarm.GetAttributeValue("name");
#Get the servers in the farm
$servers = $webFarm.GetCollection()
#Write-Host "Farm Name: " $Name
$fragments+= "<b>Farm Name: $Name</b>"
$fragments+="<br>"
foreach($server in $servers)
{
$ip= $server.GetAttributeValue("address")
$hostname= ([system.net.dns]::GetHostByAddress($ip)).hostname
#Get the ARR section
$arr = $server.GetChildElement("applicationRequestRouting")
$counters = $arr.GetChildElement("counters")
$isHealthy=$counters.GetAttributeValue("isHealthy")
$state= $counters.GetAttributeValue("state")
switch ($state)
{
0 {$state= "Available"}
1 {$state= "Drain"}
2 {$state= "Unavailable"}
default {$state= "Non determinato"}
}
if( $isHealthy)
{
$isHealthy="Healthy"
$fragments+="$hostname -- $ip -- $state -- $isHealthy"
$fragments+="<br>"
}
else
{
$isHealthy="Not Healthy"
$notHealthy="RED ALERT!! This is what we trained for!"
$fragments+="$hostname -- $ip -- $state -- $isHealthy"
$fragments+="<br>"
}
#Write-Host -NoNewLine $hostname " " $ip " " $state " " $isHealthy
#NEW LINE
#Write-Host
}
#NEW LINE
#Write-Host
if($notHealthy){
#write the results to HTML formated email
$smtpServer = "SMTP server"
$smtpFrom = "email address"
$smtpTo = "email address"
$messageSubject = "Unhealthy Web Server"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$message.Body = $fragments
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)
}
}

Recieving very slow response from twitter usertimeline requests, is the twitter API slow?

I am retrieving tweets from multiple accounts (around 20) and displaying them on a page. The request are very slow and my page takes one to two minutes to load. I am using the twitteroauth library (PHP). If i reduce the number of accounts, the loading time kind of decreases.
Here's the function
//twitter credentials and connection
$consumer_key = variable_get('tw_consumer_key', 'xxxxxxxxxxx'); //consumer key
$consumer_secret = variable_get('tw_consumer_secret', 'xxxxxxx'); // consumer secret
$oauth_token = variable_get('tw_access_token', 'xxxxxxxxxxxx'); //oAuth Token
$oauth_token_secret = variable_get('tw_access_token_secret', 'xxxxxxxxxx'); //oAuth Token Secret
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
$connection->host = "https://api.twitter.com/1.1/";
//Retrieve feeds now
foreach ($twitter_accounts as $account_twitter) {
if (!empty($account_twitter['lien'])) {
$page_url = $account_twitter['lien'];
$twitter_name = $account_twitter['compte'];
$query = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $twitter_name . '&exclude_replies=true&include_rts=true&include_entities=true';
$content = $connection->get($query);
if (sizeof($content) > 0 && empty($content->errors)) {
$tw_tweets['posts'] = $content;
$tw_tweets['url'] = $page_url;
$twitter_feeds[] = $tw_tweets;
}//end if sizeof
else {
if (!empty($content->errors)) {
$error = '';
$error = (isset($content->errors[0]->message)) ? $content->errors[0]->message : '';
$error .= (isset($content->errors[0]->code)) ? ' code' . $content->errors[0]->code : '';
watchdog('ffbb_hubsocial', 'Twitter Account ' . $account_twitter['compte'] . ' failed to return results :' . $error);
}
}
}
}
Is the API slow ?
Anyone knows if the problem is with twitter ?
Duplicate question: Why are the Twitter api calls so slow?
As the above answer states, try testing the URL in your browser and see how long it takes. Hence, you'll be able to see if the issue is on your side or due to Twitter.

Retrieving email-id from database and send mail to them

In yii i am creating sendemail functionality. I am using mailer extension and its working correctly after making all settings of SMTP. i had made method actionEmail in controller as-
public function actionEmail()
{
$model=new User;
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
$mailer->IsSMTP();
$mailer->IsHTML(true);
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = "ssl";
$mailer->Host = "smtp.gmail.com";
$mailer->Port = 465;
$mailer->CharSet = 'UTF-8';
$mailer->Username = "abc#gmail.com";
$mailer->Password = "abc";
$mailer->From = "xyz#gmail.com";
$mailer->FromName = "Balaee.com";
$mailer->AddAddress('shilpa.kirad#shailani.com');
$mailer->Subject = "welcome to Balaee";
$mailer->IsHTML(true);
// $html = $this->renderPartial('myview',array('content'=>'Hello World'),true);
$mailer->Body = "Welcomeclick on link for other detail ".$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($mailer->Send()) {
echo "Please check mail";
//Yii::app()->user->setFlash('register','Thank you for contacting us. We will respond to you as soon as possible.');
// $this->refresh();
}
else {
echo "Fail to send your message!";
}
}
This method is implementing correctly.It is sending mail to address which is mentioned in mailer->AddAdress.But now i want to retrive email id's from database corresponding to specific user's id and send mail to him. i.e.I dont want to insert hard coded value for this field. So how can i do this. Please help me.
for fetch use id of user to get email address as
$user_model=User::model()->findByPk($id);
and set in email as
$mailer->AddAddress($user_model->email_id);
where id and email_id are the table column name.
check other ways .
http://www.yiiframework.com/doc/guide/1.1/en/database.dao
For this to be done, you can fetch email id from database using following query:
$email = SELECT email FROM USER WHERE user_id = "X";
Here X is user_id of user whom you want to send email.
And provide this $email in the receipient's email field. Thanks.

sending mail from yii

public function mailsend($name, $contact_no, $email,$website,$content,$subject,$address )
{
$message = new YiiMailMessage;
$message->view = 'viewfilenm';
$message->setBody(array(), 'text/html');
$body = $message->message->getBody();
/****** preg_replace :Perform a regular expression search and replace ******/
$body = preg_replace('/\[FNAME]/',$name,$body);
$body = preg_replace('/\[CONTENT]/',$content,$body);
$find = array("[CONTACT_NO]"=>$contact_no,"[FNAME]"=>$name,"[EMAIL]"=>$email,"[ADDRESS]"=>$address);
/****** strtr :Translate characters or replace substrings ******/
$newstr = strtr($content, $find);
$body = str_replace($content,$newstr,$body);
$body = preg_replace('/\[CONTACT_NO]/',$contact_no,$body);
$body = preg_replace('/\[EMAIL]/',$email,$body);
$body = preg_replace('/\[SUBJECT]/',$subject,$body);
$body = preg_replace('/\[WEBSITE]/',$website,$body);
$message->message->setBody($body, 'text/html');
$message->subject = $subject;
$message->addTo($email);
$message->from = ('abc#abc.com');
Yii::app()->mail->send($message);
}
in $message->addTo() if I pass my gmail id then in gmail I got the mail.
but if i pass my yahoo or other id in $message->addTo() then I don't get the mail and no error also display.
If email is getting delivered to some addresses but not others, it's probably not an issue with your code. It's probably your sever.
Email delivery is complicated. Almost every endpoint (Gmail, Yahoo, etc) has different spam rules. The biggest problem you are going to face is getting the IP address you are sending from to be recognized as "safe".
I've had the best luck sending email using an established SMTP server (like Gmail) as my send agent in Yii.
Here are a some other resources about deliverability:
http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
http://www.engineyard.com/blog/2009/how-to-ensure-your-email-gets-delivered/