Actually I want to send a group mail so I have taken the mail id's from db and stored in the variable but when I try to send mail using delimeter as
',' , it shows invalid email id
Below code to Take mail id's from db:
while ($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
$word = $row['Email'];
$GetData = $GetData.$word.',';
}
Now $GetData =example1#gmail.com,example2#gmail.com
php mailer
$mail->addAddress$GetData ,user );
When I add the same into add address it is not working
Message could not be sent.Mailer Error: Invalid address: (to):example1#gmail.com,example2#gmail.com
Note:
if single id then it is sending successfully , so seems like issue with my side so need assistance on this.
You need to use addAddress for each recipient, you are kind of mixing the old headers style with the new mail object..
while ($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
$mail->addAddress($row['Email'] , '');
}
Related
I need help for this PHP script:
<?php
$link = mysql_connect('localhost', 'Username', 'PW');
$sql = "SELECT Driver, Mail FROM mytable";
$query = mysql_query($sql);
$emailBody="";
$Subject="test";
$to ="xxx";
while($row = mysql_fetch_assoc($query))
{
$emailBody .= "Driver: ".$row['Driver']."\n";
}
$to = str_replace('xxx', $row['Mail'], $to);
mail($to, $Subject, $emailBody);
I tried many things:
mail($to, $Subject, $emailBody);
mail($row['Mail'], $Subject, $emailBody);
I cannot set the field value of row['Mail'] as the receiver address.
The field values have been tested with "mymail#mail.com" and 'mymail#mail.com' and mymail#mail.com .
The replace function was just another trial.
$to =str_replace('xxx',$row['Mail'],$to);
Nothing works except hardcoding for test only..
mail("mymail#mail.com", $Subject, $emailBody);
Thanks!
$row only exists inside your loop (i.e. inside the { and }). But your $to line exists outside the loop, therefore it cannot access any values from $row.
If, as you mention in the comments, you wish to generate a separate email for each row of your query results then
a) you need to move the code which sets the recipient and sends the mail inside the loop so it can access the row data, and execute once per row
and
b) you need to not concatenate the body with data from every row, otherwise every email after the first will contain details from all the previous rows as well as the current one.
This should work better:
$link = mysql_connect('localhost', 'Username', 'PW');
$sql = "SELECT Driver, Mail FROM mytable";
$query = mysql_query($sql);
$Subject="test";
while($row = mysql_fetch_assoc($query))
{
$emailBody = "Driver: ".$row['Driver']."\n";
mail($row['Mail'], $Subject, $emailBody);
}
P.S. As I mentioned in the comments, you need to urgently replace the obsolete mysql_ calls with mysqli or PDO, and urgently upgrade to a supported version of PHP. I'd also recommend using a library like PHPMailer to handle your email sending - it's easier to work with than mail() and is more likely to generate valid emails which won't get accidentally blocked as spam etc. It can also support SMTP where mail() only supports local mailservers via sendmail.
I run this script to send to each user an email. Mails are sent ok(one to each user), but in the email sent all the others adresses are shown in the headers.
$all_users = array(); // intialzie array
while ($usuario = mysqli_fetch_array($resultado, MYSQLI_ASSOC)) {
$usermail = $usuario['email'];
$hash = $usuario['hash'];
mysqli_query($dbc, "UPDATE newsletter SET enviado = '1' WHERE email='$usermail' ");
$all_users[] = $usermail; // push all emails first
}
// then send
try {
$email->setTos($all_users)
->setFrom("no_responder#test.com.ar")
->setFromName("test")
->setReplyTo("no_responder#test.com.ar")
->setSubject("Test")
->setHtml('test');
$result = $sendgrid->send($email);
echo "enviado";
} catch(\SendGrid\Exception $e) {
echo $e->getCode() . "\n";
foreach($e->getErrors() as $er) {
echo $er;
}
}
?>
How can i hide other emails while sending them individually using sendgrid (bcc - blind carbon copy)?
Have you updated your SendGrid PHP library? The newest version uses v3 of the WebAPI, which corrects the confusing To: array functionality.
The issue is that what you're doing right now is populating the native SMTP-level To, which is why you can see all the addresses. In the v2 API, you'd need to instead populate the x-smtpapi field's to array, to make sure SendGrid splits out all the addresses.
I'd strongly recommend updating your PHP Library & leveraging the v3 API, which removes this confusion, and lets you setup each recipient in a more logical manner.
How can I make it so when a user email's to my email address their email text/information is written into a mysql table? So basically extract the contents of a new email and write them into mysql table.
I tried this but I get nothing:
<?php
$imap = imap_open("{gmail.com}", "username", "password");
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
echo imap_qprint(imap_body($imap, $num));
}
//close the stream
imap_close($imap);
}
?>
We are using an exchange server..I am a coop student so I am not really advanced at this.
I tried this as a test to see if it works, logging in gmail to read email. It didnt work.
<?php
// connect to the mailbox
$m_mail = imap_open("{mail.https://accounts.google.com/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1<mpl=default<mplcache=2}INBOX", "username", "password");
//get all messages
$m_search=imap_search ($m_mail, 'ALL ');
// Order results starting from newest message
rsort($m_search);
//loop through and do what's necessary
foreach ($m_search as $onem) {
//get imap header info for obj thang
$headers = imap_headerinfo($m_mail, $onem);
$head = imap_fetchheader($m_mail, $headers->Msgno);
$body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );
echo $body;
}
//purge messages (if necessary)
imap_expunge($m_mail);
//close mailbox
imap_close($m_mail);
?>
use IMAP functions for that. Set up another email account if necessary. Here's the example code:
// connect to the mailbox
$m_mail = imap_open("{mail.YOURHOST.com:993/imap/ssl/novalidate-cert}INBOX", "address#YOURHOST.com", "YOURPASSWORD");
//get all messages
$m_search=imap_search ($m_mail, 'ALL ');
// Order results starting from newest message
rsort($m_search);
//loop through and do what's necessary
foreach ($m_search as $onem) {
//get imap header info for obj thang
$headers = imap_headerinfo($m_mail, $onem);
$head = imap_fetchheader($m_mail, $headers->Msgno);
$body = imap_body($m_mail, $headers->Msgno, FT_INTERNAL );
//
DO WHAT YOU NEED TO DO HERE - insert to the database, etc
}
//purge messages (if necessary)
imap_expunge($m_mail);
//close mailbox
imap_close($m_mail);
read your mailbox via pop3 or imap and add the new emails to your database
Take a look a this class: http://php.net/manual/en/book.imap.php
you could read the pop3/imap in some intervals.
other method would be to redirect your email to a php script. I don't know which email system you are using on your server but here is an example with postfix.
the pop3/imap method is easier and you don't need to edit your server configs but the second method is faster because your script will start as it receives an email.
following is my script for send email inquiry.. the recipient email address was stored in a db called users.. this script will not work properly.. i think the problem is recipient email section.. because when i used a email address instead of $user it will work..
thanx help me
<?php
$refno = $HTTP_POST_VARS['refno'];
$proid = $HTTP_POST_VARS['proid'];
$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$msg = $HTTP_POST_VARS['msg'];
//connect db and find email address related to id
include 'db_connector.php';
$id=$HTTP_POST_VARS['id'];
$query=mysql_query("SELECT user_email FROM users WHERE id='".$id."'");
$cont=mysql_fetch_array($query);
$user=$cont['user_email'];
// recipient name
$recipientname = "'".$name."'";
// recipient email
$recipientemail = $user ;
// subject of the email sent to you
$subject = "Inquiry for your advertisement No. (".$refno.")";
// send an autoresponse to the user?
$autoresponse = "no";
// subject of autoresponse
$autosubject = "Thank you for your inquiry!";
// autoresponse message
$automessage = "Thank you for your inquiry.! We'll get back to you shortly.
";
// END OF NECESSARY MODIFICATIONS
$message = "reference number : $refno
$msg
From $name $email
---";
// send mail and print success message
mail($recipientemail,"$subject","$message","From: $recipientname <$email>");
if($autoresponse == "yes") {
$autosubject = stripslashes($autosubject);
$automessage = stripslashes($automessage);
mail($email,"$autosubject","$automessage","From: $recipientname <$recipientemail>");
}
header("Location:index.php");
exit;
?>
First of all, your query is SQL injectable. Never ever pass a variable coming from a POST request directly into an SQL query. Use mysql_real_escape().
As to your bug: it seems that $user does not contain a valid e-mail address. so, the Mysql query is not returning an e-mail address.
Use $_POST rather than $HTTP_POST_VARS.
Switch on error reporting by prepending these two lines to your PHP code:
PHP code:
error_reporting(E_ALL);
ini_set('display_errors','1');
Run your script again. Do you get any notices or warnings?
If not, try to display your query, by adding
die($query);
just before the line that has the mysql_query command, and then run the query manually (e.g. using PhpMyAdmin or MySQL Query Browser) to see if you are actually getting a result that looks like an e-mail address.
Debug your PHP program.
Check out :
If the variables contain the supposed values.
Query is okay and returns result.
Proper header is set with mail function.
etc.
PHP manual have a good example to send mail.
Do not use $HTTP_POST_VARS['name']; it is deprecated use $_POST instead.
hey guys thanx for the help.. i found the error done in my inquiry form.. the id filed hidden outside of the form tag.. therefore the id value will not passed to the sendinq.php. i change it thank now the sendmail option work properly
I'm using zend mail extended with zend_mail_storage_imap and I built an application that looks for keywords in user's emails.
The problem is that it opens up each email and keeps it marked as read. Is there a way to check the body of emails and not mark each mail checked as read?
Here's current working code. It's part of an ajax query that automatically looks through someone's inbox. In this current form, it will mark each mail starting with a user's most current mail as read (in gmail). Would it be possible to check the body text, but not mark the email as read. Alternatively, will I need to check if each mail is read or unread before looking it up, and then restore it to that state as a workaround?
if (strpos(htmlentities($storage->getMessage($i)),$searchterm))
{
$fromaddress = str_replace("'","",$storage->getMessage($i)->from);
$fromaddress = str_replace('"','',$fromaddress);
$sql = "SELECT `senderemail`,`subscribed` FROM email_spam WHERE `useremail` = '$_SESSION[email_address]' AND `senderemail` = '$fromaddress'";
$result = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($result);
if($num == 0)
{
$emailmessage = mysql_escape_string($storage->getMessage($i)->getContent());
$sql_insert = "INSERT into `email_spam` (`message`,`useremail`,`senderemail`,`datetime`,`subscribed`) VALUES ('$emailmessage','$_SESSION[email_address]','$fromaddress',now(),1)";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
$sql = "SELECT `emailid`,`datetime` FROM email_spam WHERE `useremail` = '$_SESSION[email_address]' ORDER BY `datetime` desc";
$getid = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($getid);
}
}
EDIT - here's the final code for those interested
$storage = new Zend_Mail_Storage_Imap($imap);
$flags = $storage->getMessage($i)->getFlags();
$newflag = $flags[Zend_Mail_Storage::FLAG_RECENT];
$oldflag = $flags['\Seen'];
if(!empty($flags['\Seen']))
{
$read=1;
}
else
{
$read=0;
}
The entire code is looped, so here, I perform my entire searching/sorting algorithm for each individual email.
if ($read==0)
{
$storage->setFlags($i, array(Zend_Mail_Storage::FLAG_RECENT)); //marks as new
}
Here, I go and mark the emails that were not read (before the implementations) as unread. I think this is the most efficient way (that I could find) of performing this operation. I welcome any other codes or comments.
After reading a message, you could unset the seen flag. See also the imap implementation of the setFlags method. Api documentation
To unset the "seen" flag:
$flags = $msg->getFlags();
unset($flags[Zend_Mail_Storage::FLAG_SEEN]);
$storage->setFlags($i, $flags);
Setting the "recent" flag does not necessarily do what you want it to! On gmail, it will mark emails as "important".
When reading mails with the IMAP Storage in Zend Framework you have access to a method called setFlags in Zend_Mail_Storage_Imap
I don't think it's documented in the ZF manual but you might want to look into the API docs (see link above) to set the status/flag on a message.
You could also just use empty array to reset any flags
$mailstorage->setFlags($messageID, array());
Flag change seem to be done via getContent() method after fetching the message in zend-mail 2. Below is an example to read content and keep initial flags :
$imap = [
'host' => $connection['mailhost'],
'user' => $connection['username'],
'password' => $password,
];
$storage = new \Zend\Mail\Storage\Imap($imap);
$lastMsgIndex = $storage->countMessages();
$msg = $storage->getMessage($lastMsgIndex);
$msgFlags = $msg->getFlags();
// Line below will mark email as seen if getContent is called
$content = $msg->isMultipart() ? 'Multipart Email' : $msg->getContent();
$storage->setFlags($lastMsgIndex, $msgFlags);