I'm trying to use sendgrid to send emails from my app. To add email addresses via php, according to the sendgrid docs, you use the following:
$email = new SendGrid\Email();
$email
->addTo("example#email.com")
where addTo is used for each email address. I would like like to generate the addTo list dynamically, for example I have a list of 3 emails in a php variable that I would like to send mails to:
$email_addresses = 'example#email1.com, example#email2.com. example#email3.com';
I've tried the following to echo out individual ->addTo properties per email address however it doesn't work:
$email = new SendGrid\Email();
$email
$string = $email_addresses;
$string = preg_replace('/\.$/', '', $string); //Remove dot at end if exists
$array = explode(', ', $string); //split string into array seperated by ', '
foreach($array as $value) //loop over values
{
echo '->addTo("'.$value.'")<br>';
}
Does anyone know what I'm doing wrong here?
There's a setTos method in sendgrid-php that handles arrays: https://github.com/sendgrid/sendgrid-php#settos
Related
I'm trying to send emails after a post creation but trying to omit sending email to the creator of the post.
I get demo3#demo.com, demo2#demo.com, demo4#demo.com by doing
$emails = rtrim($emails,', ');
I'm trying to remove demo3#demo.com
$owners_email = Session::get('user_email'); // which is demo3#demo.com
$emails = rtrim($emails,$owners_email);
but I get demo3#demo.com, demo2#demo.com, demo4
$emails = join(', ', array_diff(array_map('trim', explode(',', $emails)), [$owners_email]));
In detail, you can do these steps individually if you want:
explode(',', $emails): turn your email list into an array
array_map('trim', ...): remove whitespace from the emails
array_diff(..., [$owners_email]): remove the owner's email from the array
join(', ', ...): collapse the emails back into a list
How about this?
http://php.net/manual/en/function.str-replace.php
str_replace($owners_email.",","",$emails);
I'm trying to get addresses from a simple text file, so people who don't understand code can still add/remove or change the adresses.
Phpmailer is working totally fine when I set up an address normally, writing it directly in the code, and even with an array and a foreach.
So at the moment I have this :
mail.php :
//all phpmailer settings on $mail var
$addresses = file('mail.txt', FILE_IGNORE_NEW_LINES);
foreach($addresses as $email) {
echo "$email<br>";
$mail->addAddress($email);
}
mail.txt :
'first#address.com'
'second#address.fr'
The echo does return both addresses but the var doesn't seem to work in the addAddress() line, and I get the usual error :
Mailer Error: You must provide at least one recipient email address.
Thanks for correcting me if I'm wrong or if you know any other solution that could work !
Okay so here is the working code corrected with the help of Waqas Shahid :
mail.php :
//all phpmailer settings on $mail var
$addresses = file('mail.txt', FILE_IGNORE_NEW_LINES);
foreach($addresses as $email) {
$email = trim($email);
$change = array('\n', '\t', '\r');
$email = str_replace($change, "", $email);
$mail->addAddress($email);
}
mail.txt :
first#address.com
second#address.fr
You should remove single quotes first, then get value line by line and remove whitespaces using trim() then remove '\n', '\t', '\r' using str_replace()
From a multi-line text field I get several email addresses separated by new line. Field value is stored in database as a JSON string:
{"admin_emails":"email1#domain.com\r\nemail2#domain.com"}
Then I decode the emails using json_decode and explode:
$emailStr = json_decode($stringFromDb)->admin_emails;
$emails = explode("\r\n", str_replace("\r", "\r\n", $emailStr) );
next, for each email in table, I check if it's valid and do some stuff:
foreach( $emails as $email )
{
if( filter_var($email, FILTER_VALIDATE_EMAIL) ){
// do stuff with email
}
}
But I have following problem: only the first email is recognized by the filter_val as valid email address. All subsequent emails are filtered out. What causes that these emails are not recognized as valid e-mail addresses?
It looks like you're replacing "email1#domain.com\r\nemail2#domain.com" with "email1#domain.com\r\r\nemail2#domain.com" - In other words \r\r\n. So all emails after the first start with a line break and thus are invalid.
You could simply do without the str_replace() all together
Maximus is correct:
<?php
$s ='{"admin_emails":"email1#domain.com\r\nemail2#domain.com"}';
//Then I decode the emails using json_decode and explode:
$emailStr = json_decode($s)->admin_emails;
$emails = explode("\r\n", $emailStr);
//next, for each email in table, I check if it's valid and do some stuff:
foreach( $emails as $email ) {
if( filter_var($email, FILTER_VALIDATE_EMAIL) ){
echo $email." is valid\n\n";
// do stuff with email
}
}
This yields:
email1#domain.com is valid
email2#domain.com is valid
I'm working on a template for use in my email system. And i'll send mails to my customers.
This will be my create-email.php file :
and will have a textarea, i need some variables for use on it;
Hello {firstname} {lastname},
Your email address {email} has been added in to our newsletter list.
You can unsubscribe with using this link :
http://example.com/unsubscribe.php?memberid={memberid}&email={email}
This textarea will be POST'ed to send-email.php
and my problem is starting here. I want to replace the {firstname} {lastname} {email} {memberid} with my data's coming from my database.
How can i do this ?
Use str_replace with an array of values.
// $array can be set from a query perhaps?
$array = array('firstname' => 'Bob', 'lastname' => 'Dave',...);
// $template could also be a string which is a large block such as yours above.
$template = file_get_contents($template);
foreach($array as $key => $value) {
$template = str_replace("{$key}", $value, $template);
}
You can also do this with using two arrays, but I do not actually advocate this as its using more memory and is problematic when keeping track of what field matches what value.
// Array of fields to replace
$fields = array('firstname', 'lastname',...);
$values = array('bob', 'dave',...);
$template = file_get_contents($template);
$template = str_replace($fields, $values, $template);
This little Goldie is perfect for you :)
<?php
$email_content = $_POST['email_content'];
$search = array('{firstname}', '{lastname}', '{email}', '{memberid}');
$replace = array('Christian', 'Sany', 'email#email.com', '123123123');
$replaced_content = str_replace($search, $replace, $email_content);
?>
I am piping email that get's sent to my server to a PHP script. The script parses the email so I can assign variables.
My problem is once in awhile somebody will include my email address to an email that's getting sent to multiple recipients and my script will only get the first one. I need it to find my email address then assign it to a variable.
Here is what the email array looks like: http://pastebin.com/0gdQsBYd
Using the example above I would need to get the 4th recipient: my_user_email#mydomain.com
Here is the code I am using to get the "To -> name" and "To -> address"
# Get the name and email of the recipient
$toName = $results['To'][0]['name'];
$toEmail = $results['To'][0]['address'];
I assume I need to do a foreach($results['To'] as $to) then a preg_match but I am not good with regular expressions to find the email I want.
Some help is appreciated. Thank you.
Instead of usin preg_match inside foreach loop you can use strstr like below
Supposing you are looking for my_user_email#mydomain.com use following code
foreach($results['To'] as $to)
{
// gets value occuring before the #, if you change the 3 rd parameter to false returns domain name
$user = strstr($to, '#', true) ;
if($user == 'my_user_email')
{
//your action code goes here
}
}
example:
<?php
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
$user = strstr($email, '#', true); // As of PHP 5.3.0
echo $user; // prints name
?>
Actually, you do not need to use a regexp at all. Instead you can use a PHP for statement that loops through your array of To addresses.
$count = count($root['To']);
for ($i=0; $i < $count; $i++) {
//Do something with your To array here using $root['To'][$i]['address']
}