Add Emails to a Database when Received (PHP) - php

I want to make it so users can automatically subscribe to my mailing list by sending a email with a special body.
Example:
Send "subscribe" to "email#mywebsite.com" and a PHP script is automatically executed to add them to a database.
Send "unsubscribe" to "email#mywebsite.com" and the PHP script removes them.
I have the script to add/remove them done easily, but what I need help with is how to actually implant the email receive to execute the function...If that makes sense.
Using cPanel/WHM, can do a cron job.
Thanks a lot for the help

The solution can be the following code (i didn't check it):
if( $imap ) {
//Check no.of.msgs
$num = imap_num_msg($imap);
//if there is a message in your inbox
if( $num >0 ) {
//read that mail recently arrived
if (imap_qprint(imap_headerinfo($imap, $num)) == 'subscribe'){
// code for add user to database
};
if (imap_qprint(imap_headerinfo($imap, $num)) == 'unsubscribe'){
// code for delete user to database
}
}
//close the stream
imap_close($imap);
}
?>

Related

send mail via php yii until success on time

i have php function that send mail on special time ever 7 days but when i send mail its sometimes not sent because server busy or not available ,my question is how to try send my email many times when its something wrong every 10 minute until its send success
private function sendEMailMessage($args) {
$failed = true;
for($i = 0; $i < 5 && $failed; $i ++) {
$failed = Utilities::sendEMailMessage ( $args ) != '';
if ($failed) {
sleep ( 15 );
}
}
}
//its this work or not ???
The another way you can do this is setting a flag in database table. Based on the flag value you can send/resend the email. On successful sending of email you can delete or reset the flag .
The best way to deal with this problem would be to set up cron jobs for every 7 days.And for the mail sometimes getting not sent purpose you could use this,
if (Yii::$app->mailer->getTransport()->isStarted()) {
Yii::$app->mailer->getTransport()->stop();}
Yii::$app->mailer->getTransport()->start();
If this is included in your yii app then once the mail is sent it should clear the ssl socket layer and open a fresh socket again for the next time.With the combined use of these I think it should work.

How can I send an email to lots of users using a proper way in CodeIgniter 3

I need some advice because I am building a subscription module. And I have a list of so many emails. Let say 1052 emails. And I have a code like this:
$email_list = $this->getClientEmails(); //all email for now returns 1052 valid emails
$valid_email = array();
$invalid_email = array();
if(count($email_list) > 0) {
for($x = 0; $x < count($email_list); $x++) {
if(valid_email($email_list[$x]['email'])) {
$valid_email[] = $email_list[$x]['email'];
}
//get all invalid emails
/*else {
$invalid_email[] = array(
'id' => $email_list[$x]['id'],
'email' => $email_list[$x]['email']
);
}*/
}
}
$email_string = implode(',', $valid_email);
$this->email->set_mailtype("html");
$this->email->from($from, 'Sample Admin');
$this->email->to($email_string); //send an email to 1052 users
$this->email->cc('test#sampleemail.com.ph');
$this->email->subject($subj);
$this->email->message($content);
$send_mail = $this->email->send();
if($send_mail) {
fp('success');
} else {
fp('failed');
}
Is it fine if I send an email like this? Or should I make a loop to send my email to different users? Means I will not use my imploded string. I will do the sending once in every week. And also what if the sending of email suddenly stops in the middle what should I do? Do I need to resend it again? Or should I make a column in my table that will update if the email is sent or not?
Can you give me some advice about this? That's all thanks.
Okay because you have a mailing list the first thing that i would recommend is that you push the script to background. Use selinium or cron for the same that way page render won't get stuck.
Once done You can send emails either way, send to multiple people or one at a time, both of them are valid and won't cause any problem. The point you need to consider here is the SMTP connection that you maintain.
If you are sending them all individually, you don't want to close connection to SMTP server and reconnect every time to send the mail which would only cause the overhead.
I should say that from your case the most valid way to send email is make a queue on some database preferably redis and have a task handle them in background (cron job if you are on cpanel or selinium if you own the server)
Finally this is a part that you might wanna test out. Because you have a mailing list i am guessing you don't want people to see through your whole list so check the headers when you are sending mails to all at once and if you don't see email from other users , you are good to go else send to each of them separately.
Also one final thing, emails not being delivered is usually bounced which may reflect bad on your server so have a script that flags emails that are constantly rejected and stop sending mails to the same or your ip address might end with bad repo and mails might end up in spam.
Have you thought of using PHPMailer as a library on your CodeIgniter installation?
You could just do it like this:
if(count($email_list) > 0) {
for($x = 0; $x < count($email_list); $x++) {
if(valid_email($email_list[$x]['email'])) {
$mail->addAddress($email_list[$x]['email'], $x);
}
}
}
Please refer to this example on how to use PHPMailer.
I hope this helps, or at least that it gives you a different perspective on how can this be done.
Referring to:
Or should I make a column in my table that will update if the email is sent or not?
Yes, I think that if you want to control if an email has been sent you should use a 1 character field on your table as a "flag" to corroborate that the email has been sent to your users.

Can't use an array in Swift Mailer function

I'm using Swift Mailer to send emails to users. I've following script to send email to a number of users at a time.
$j=0;
while($row = mysql_fetch_assoc($email))
{
$message[$j]->addTo($row['email_invited']);
$mailer->send($message[$j]);
$j++;
}
I get the following error while doing this:
Fatal error: Cannot use object of type Swift_Message as array in
/home/public_html/example.com/people.php on line 21
If I try to send emails like this:
while($row = mysql_fetch_assoc($email))
{
$message->addTo($row['email_invited']);
}
$mailer->send($message);
It sends the email normally & every user gets it but the issue with that is every user can see what other users have got the email along with him. So basically in "To" field, every email is bound & thus every users gets to see all other email addresses.
What I want to achieve is every user should get a personalized email only even though it's sent in bulk. That is why I tried to use array & separate email but getting error in that.
Any idea how to achieve that?
How about doing. I think you need to create new instance of message (and maybe mailer too) in every loop.
while($row = mysql_fetch_assoc($email))
{
$mailer = Swift_Mailer::newInstance($transportName);
$message = Swift_Message::newInstance($subject);
$message->addTo($row['email_invited']);
$mailer->send($message);
}

How to send a message securely via html and php (post)

I use a php code on my server to send messages to my clients. The programming tool I use (Game Maker) allows me to send messages via php by executing a shell so that the link appears in a browser.
Example is here ...
with all the other stuff added. So in effect, the message I'm sending and all the stuff I'm sending are seen in the browser. I use the php get method. everything works perfectly now, except that it may not be secured. Someone suggested php post method, but when I replaced get in my php cod on my server to post, and pasted the same thing in the browser, my code didn't work. It's hard to explain, but here's the php code on my server:
<?php
// Some checks on $_SERVER['HTTP_X_REFERRER'] and similar headers
// might be in order
// The input form has an hidden field called email. Most spambot will
// fall for the trap and try filling it. And if ever their lord and master checks the bot logs,
// why not make him think we're morons that misspelled 'smtp'?
if (!isset($_GET['email']))
die("Missing recipient address");
if ('' != $_GET['email'])
{
// A bot, are you?
sleep(2);
die('DNS error: cannot resolve smpt.gmail.com');
// Yes, this IS security through obscurity, but it's only an added layer which comes almost for free.
}
$newline = $_GET['message'];
$newline = str_replace("[N]","\n","$newline");
$newline = str_replace("[n]","\n","$newline");
// Add some last-ditch info
$newline .= <<<DIAGNOSTIC_INFO
---
Mail sent from $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT]
DIAGNOSTIC_INFO;
mail('info#site.com','missing Password Report',$newline,"From: ".$_GET['from']);
header( 'Location: http://site.com/report.html' ) ;
?>
I then call this php code on my site. so that in the end, the whole thing ends up in the browser address bar. I hope this makes sense. How do I make things more secured by using post so that at least the sent information cannot be seen in users history and all that.
If you replace to POST in your form you need to replace the request to POST too:
<?php
// Some checks on $_SERVER['HTTP_X_REFERRER'] and similar headers
// might be in order
// The input form has an hidden field called email. Most spambot will
// fall for the trap and try filling it. And if ever their lord and master checks the bot logs,
// why not make him think we're morons that misspelled 'smtp'?
if (!isset($_POST['email']))
die("Missing recipient address");
if ('' != $_POST['email'])
{ // A bot, are you?
sleep(2);
die('DNS error: cannot resolve smpt.gmail.com');
// Yes, this IS security through obscurity, but it's only an added layer which comes almost for free.
}
$newline = $_POST['message'];
$newline = str_replace("[N]","\n","$newline");
$newline = str_replace("[n]","\n","$newline");
// Add some last-ditch info
$newline .= <<<DIAGNOSTIC_INFO
---
Mail sent from $_SERVER[REMOTE_ADDR]:$_SERVER[REMOTE_PORT]
DIAGNOSTIC_INFO;
mail('info#site.com','missing Password Report',$newline,"From: ".$_POST['from']);
header( 'Location: http://site.com/report.html' ) ;
?>
Unless you are sending it with real GET parameters like http://www.mysite.com/send.php?email=etc; in this case you do need to set it to GET to retrieve the variables.

Email with PHP after conditional statement

So, I'm trying to do a very simple thing - send an email using PHP. I've looked through other queries on stack and none of them involve a conditional statement, so I wanted to check and see if I could get some quick advice. See the conditional below that then send a confirmation / thank you email to someone who donated to my organization.
Could it be that I first have the code echoing / printing a statement and then running the mail() function?
if ((isset($_POST['submitted'])) && ($ack!="SUCCESS")) {
$_SESSION['reshash']=$resArray;
$location = "https://globalcitizenyear.org/wp-content/themes/deMar/APIError.php";
header("Location: $location");
} elseif ($ack =="SUCCESS") {
echo ("<h2>Thank You</h2><p>Thank you for your generous donation of $$amount. You will receive an email confirmation with an attached tax receipt.</p>");
$body = "Dear $firstName,
/n/nThank you ...
/n/nAs I travel the country, ...
/n/nPlease accept my deepest gratitude for your contribution.
/n/nSincerely,
/n/nAbigail Falik
/n/nFounder and CEO
/nGlobal Citizen Year";
**$body = wordwrap($body,70);
mail("$email",'Thank you for your donation to Global Citizen Year (Important tax receipt)', $body,"From:donations#globalcitizenyear.org");**
}
else {
// Display Form ?>
Your code looks ok. It's best to send the mail first and check whether the function was successful. Then you can echo out "You will receive an email confirmation..." if successful, and some other message if the mail() call failed. With the mail() function, though, problems are usually later in the mail process. Getting a 'true' return from that function doesn't mean that Everything has worked in the email world.
With other functions, like DB writes, you will get a solid success or failure returned from the function and should act on it appropriately. That means you want to run the function before printing out a message saying everything went fine.

Categories