I'm using sendgrid with php, I've used both options the client library and the curl option. So far, I've been able to send emails directly with the addTo option with no problem. But when I try to add Cc or Bcc options, the email still gets sent but the copies are never delivered. Are there any known issues with the php version? In other project the java library works just fine.
Here is a simple piece of code I'm trying to make it work
<?php
require ('sendgrid/sendgrid-php.php');
$sendgrid = new SendGrid('user', 'pwd');
$mail = new SendGrid\Email();
$mail ->addTo("mymail#gmail.com");
$mail ->addCc("other#otherserver.com");
$mail ->setFrom("sender#server.com");
$mail ->setSubject("TEST");
$mail->setHtml("<h1>Example</h1>");
$sendgrid->send($mail);
?>
The documentation does not seem to have addCc method.
You can try these alternatives.
$mail = new SendGrid\Email();
$mail->addTo('foo#bar.com')->
addTo('someotheraddress#bar.com')->
addTo('another#another.com');
or
$mail = new SendGrid\Email();
$mail->addBcc('foo#bar.com');
$sendgrid->send($mail);
https://github.com/sendgrid/sendgrid-php#bcc
Find script with CC and BCC
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test#example.com", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("test#example.com", "Example User");
$email->addCc("test#example.com", "Example User");
$email->addBcc("test#example.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
Related
I have simple sendgrid php script to send email, only issue here is that i need to add more recipients, so this code works only for one recipient, i was looking at official documentation but was unable to find any useful info, is there anyone who knows how and what i need to change here to add more recipients/emails.
function sendEmail($subject, $to, $message) {
$from = new SendGrid\Email(null, "sample#email.com");
$subject = $subject;
$to = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/html", $message);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = 'MY_KEY';
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
}
The SendGrid\Mail class supports adding multiple to addresses through the SendGrid\Personalization class.
You can see an example here: https://github.com/sendgrid/sendgrid-php/blob/master/examples/helpers/mail/example.php#L31-L35
Think of a Personalization as the envelope for your email. It holds the recipient's addresses and other similar data. Each Sendgrid\Mail object, must have at least one Personalization.
Through the constructor you are using, a Personalization object is already created for you, see here: https://github.com/sendgrid/sendgrid-php/blob/master/lib/helpers/mail/Mail.php#L951-L958
You can create a Mail object without this and later add your own Personalization.
In the end, this is how I have managed to do this and it's working good.
function sendEmail($subject, $to, $message, $cc)
{
$from = new SendGrid\Email(null, "sample#email.com");
$subject = $subject;
$to = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/html", $message);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
foreach ($cc as $value) {
$to = new SendGrid\Email(null, $value);
$mail->personalization[0]->addCC($to);
}
$apiKey = 'MY_KEY';
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
}
If someone is still looking for an answer to how to add multiple emails in To, Cc, and Bcc, Using SendGrid, here is what helped me.
First, you need to add an associative array like this:
for multiple emails in to (recipients):
$tos = [
"example1#example.com" => "User 1",
"example1#example.com" => "User 2"
];
and in your SendMail class use this $email->addTos($tos); instead of $email->addTo;
Similarly, for multiple Cc use
$email->addCcs($cc);
and for Bcc
$email->addBccs($bcc);
Here is the link to see more details sendgrid php
function makeEmail($to_emails = array(),$from_email,$subject,$body) {
$from = new SendGrid\Email(null, $from_email);
$to = new SendGrid\Email(null, $to_emails[0]);
$content = new SendGrid\Content("text/plain", $body);
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$to = new SendGrid\Email(null, $to_emails[1]);
$mail->personalization[0]->addTo($to);
return $mail;
}
function sendMail($to = array(),$from,$subject,$body) {
$apiKey = 'your api key';
$sg = new \SendGrid($apiKey);
$request_body = makeEmail($to ,$from,$subject,$body);
$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());
}
$to = array('test1#example.com','test2#example.com');
$from = 'from#example.com';
$subject = "Test Email Subject";
$body = "Send Multiple Person";
sendMail($to ,$from,$subject,$body);
Now Sendgrid provides an easy way for sending single mail to multiple recipients,
it provides Mail::addTos method in which we can add multiple mails to whom we want to send our mail,
we have to pass associative array of user emails and user names into addTos.
see below example:
$tos = [
//user emails => user names
"user1#example.com" => "Example User1",
"user2#example.com" => "Example User2",
"user3#example.com" => "Example User3"
];
$email->addTos($tos);
If you want to see Full example which is provided in sendgrid-php github library then i have included it below, so you can understand the whole example:
<?php
require 'vendor/autoload.php'; // If you're using Composer (recommended)
// Comment out the above line if not using Composer
// require("<PATH TO>/sendgrid-php.php");
// If not using Composer, uncomment the above line and
// download sendgrid-php.zip from the latest release here,
// replacing <PATH TO> with the path to the sendgrid-php.php file,
// which is included in the download:
// https://github.com/sendgrid/sendgrid-php/releases
$email = new \SendGrid\Mail\Mail();
$email->setFrom("test#example.com", "Example User");
$tos = [
"test+test1#example.com" => "Example User1",
"test+test2#example.com" => "Example User2",
"test+test3#example.com" => "Example User3"
];
$email->addTos($tos);
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid(getenv('SENDGRID_API_KEY'));
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage(). "\n";
}
Ref:
https://github.com/sendgrid/sendgrid-php/blob/master/USE_CASES.md#send-an-email-to-multiple-recipients
I am using phpmailer to send email from my online website.but when i sending it showing default server address in from address
<?php
require_once 'phpmailer/class.phpmailer.php';
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try {
$mail->AddAddress('to#domain.com', 'Jo');
$mail->SetFrom('info#mydomain.com', 'Info');
$mail->AddReplyTo('name#yourdomain.com', 'First Last');
$mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML('Helooo');
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
now it showing like
i want to replace red marked address to info#mydomain.com....how can i do that...this red marked address is default server address i think. i tried to set address using phpmailer from tag, but no change
try this to change from address
<?php
$to = "somebody#example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: info#domain.com";
mail($to,$subject,$txt,$headers);
?>
It's very common for hosted email services (e.g. gmail) to not let you change the From address, or restrict you to pre-set aliases, not allowing arbitrary addresses.
It also looks like you've based your code on an obsolete example, and you're probably using an old version of PHPMailer, so get the latest version.
I am using https://github.com/google/google-api-php-client and I want to send a test email with a user's authorized gmail account.
This is what I have so far:
$msg = new Google_Service_Gmail_Message();
$msg->setRaw('gp1');
$service->users_messages->send('me', $msg);
This results in a bounce email because I have no clue how to set the raw message. I see the bounce in the inbox of my authenticated user. I want to learn how to set values for 'To', 'Cc', 'Bcc', 'Subject', and 'Body' of the email. I believe I will need to do a 64 encoding on that raw data as well. And I might want to use some html in the body of my email.
Please help to provide a working example of sending an email using the gmail-api and the google-api-php-client.
Here is the bounced email in the inbox:
Bounce -nobody#gmail.com- 12:58 PM (7 minutes ago)
to me
An error occurred. Your message was not sent.
‚ Date: Thu, 24 Jul 2014 10:58:30 -0700 Message-Id: CABbXiyXhRBzzuaY82i9iODEiwxEJWO1=jCcDM_TH-
I asked a more specific question which has led me to an answer. I am now using PHPMailer to build the message. I then extract the raw message from the PHPMailer object. Example:
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$subject = "my subject";
$msg = "hey there!";
$from = "myemail#gmail.com";
$fname = "my name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress("tosomeone#somedomain.com");
$mail->AddReplyTo($from,$fname);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
I've used this solution as well, worked fine with a few tweaks:
When creating the PHPMailer object, the default encoding is set to '8bit'.
So I had to overrule that with:
$mail->Encoding = 'base64';
The other thing i had to do was tweaking the MIME a little to make it POST ready for the Google API, I've used the solution by ewein:
Invalid value for ByteString error when calling gmail send API with base64 encoded < or >
Anyway, this is how I've solved your problem:
//prepare the mail with PHPMailer
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
//supply with your header info, body etc...
$mail->Subject = "You've got mail!";
...
//create the MIME Message
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
//create the Gmail Message
$message = new Google_Service_Gmail_Message();
$message->setRaw($mime);
$message = $service->users_messages->send('me',$message);
Perhaps this is a bit beyond the original question, but at least in my case that "test email" progressed to regularly sending automated welcome emails "from" various accounts. Though I've found much that is helpful here, I've had to cobble things together from various sources.
In the hope of helping others navigate this process, here's a distilled version of what I came up with.
A few notes on the following code:
This assumes that you've jumped through the hoops to create and download the JSON for a Google Service Account (under credentials in the developer dashboard it's the bottom section.)
For clarity, I've grouped all the bits you should need to set in the "Replace this with your own data" section.
That me in the send() method is a key word that means something like "send this email with the current account."
// This block is only needed if you're working outside the global namespace
use \Google_Client as Google_Client;
use \Google_Service_Gmail as Google_Service_Gmail;
use \Google_Service_Gmail_Message as Google_Service_Gmail_Message;
// Prep things for PHPMailer
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
// Grab the needed files
require_once 'path/to/google-api/vendor/autoload.php';
require_once 'path/to/php-mailer/Exception.php';
require_once 'path/to/php-mailer/PHPMailer.php';
// Replace this with your own data
$pathToServiceAccountCredentialsJSON = "/path/to/service/account/credentials.json";
$emailUser = "sender#yourdomain.com"; // the user who is "sending" the email...
$emailUserName = "Sending User's Name"; // ... and their name
$emailSubjectLine = "My Email's Subject Line";
$recipientEmail = "recipient#somdomain.com";
$recipientName = "Recipient's Name";
$bodyHTML = "<p>Paragraph one.</p><p>Paragraph two!</p>";
$bodyText = "Paragraph one.\n\nParagraph two!";
// Set up credentials and client
putenv("GOOGLE_APPLICATION_CREDENTIALS={$pathToServiceAccountCredentialsJSON}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
// We're only sending, so this works fine
$client->addScope(Google_Service_Gmail::GMAIL_SEND);
// Set the user we're going to pretend to be (Subject is confusing here as an email also has a "Subject"
$client->setSubject($emailUser);
// Set up the service
$mailService = new Google_Service_Gmail($client);
// We'll use PHPMailer to build the raw email (since Google's API doesn't do that) so prep it
$mailBuilder = new PHPMailer();
$mailBuilder->CharSet = "UTF-8";
$mailBuilder->Encoding = "base64";
// Not set up the email you want to send
$mailBuilder->Subject = $emailSubjectLine;
$mailBuilder->From = $emailUser;
$mailBuilder->FromName = $emailUserName;
try {
$mailBuilder->addAddress($recipientEmail, $recipientName);
} catch (Exception $e) {
// Handle any problems adding the email address here
}
// Add additional recipients, CC, BCC, ReplyTo, if desired
// Then add the main body of the email...
$mailBuilder->isHTML(true);
$mailBuilder->Body = $bodyHTML;
$mailBuilder->AltBody = $bodyText;
// Prep things so we have a nice, raw message ready to send via Google's API
try {
$mailBuilder->preSend();
$rawMessage = base64_encode($mailBuilder->getSentMIMEMessage());
$rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); // url safe
$gMessage = new Google_Service_Gmail_Message();
$gMessage->setRaw($rawMessage);
// Send it!
$result = $mailService->users_messages->send('me', $gMessage);
} catch (Exception $e) {
// Handle any problems building or sending the email here
}
if ($result->labelIds[0] == "SENT") echo "Message sent!";
else echo "Something went wrong...";
Create the mail with phpmailer works fine for me in a local enviroment. On production I get this error:
Invalid value for ByteString
To solve this, remove the line:
$mail->Encoding = 'base64';
because the mail is two times encoded.
Also, on other questions/issues I found the next:
use
strtr(base64_encode($val), '+/=', '-_*')
instead of
strtr(base64_encode($val), '+/=', '-_,')
I Used https://developers.google.com/gmail/api/v1/reference/users/messages/send
and able to send email successfully.
I am trying to modify the phpmailer db mailer to use sendmail, would this code be correct below ?. I am trying to implement it into a website to email a clientbase of around 2-300 contacts.
Thanks :-)
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom('list#mydomain.com', 'List manager');
$mail->AddReplyTo('list#mydomain.com', 'List manager');
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$query = "SELECT full_name, email, photo FROM employee WHERE id=$id";
$result = #MYSQL_QUERY($query);
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["full_name"]);
$mail->AddStringAttachment($row["photo"], "YourPhoto.jpg");
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
This should work, but make sure this feature is supported by the hosting company.
how i can access my gmail account through my php code? I need to get the subject and the from address to from my gmail account.And then i need to mark the accessed as read on gmail
Should i use gmail pop3 clint?is that any framework that i can use for accessing gmail pop3
server.
I would just use the PHP imap functions and do something like this:
<?php
$mailbox = imap_open("{imap.googlemail.com:993/ssl}INBOX", "USERNAME#googlemail.com", "PASSWORD");
$mail = imap_search($mailbox, "ALL");
$mail_headers = imap_headerinfo($mailbox, $mail[0]);
$subject = $mail_headers->subject;
$from = $mail_headers->fromaddress;
imap_setflag_full($mailbox, $mail[0], "\\Seen \\Flagged");
imap_close($mailbox);
?>
This connects to imap.googlemail.com (googlemail's imap server), sets $subject to the subject of the first message and $from to the from address of the first message. Then, it marks this message as read. (It's untested, but it should work :S)
This works for me.
<?php
$yourEmail = "you#gmail.com";
$yourEmailPassword = "your password";
$mailbox = imap_open("{imap.gmail.com:993/ssl}INBOX", $yourEmail, $yourEmailPassword);
$mail = imap_search($mailbox, "ALL");
$mail_headers = imap_headerinfo($mailbox, $mail[0]);
$subject = $mail_headers->subject;
$from = $mail_headers->fromaddress;
imap_setflag_full($mailbox, $mail[0], "\\Seen \\Flagged");
imap_close($mailbox);
?>
You can use IMAP from PHP.
<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
or die("can't connect: " . imap_last_error());
$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");
echo gettype($status) . "\n";
echo $status . "\n";
imap_close($mbox);
?>
Another nice IMAP example is available at http://davidwalsh.name/gmail-php-imap
Zend Framework has the Zend_Mail API for reading mail as well. It makes it easy to switch protocols if need be (POP3, IMAP, Mbox, and Maildir). Only the IMAP and Maildir storage classes support setting flags at this time.
http://framework.zend.com/manual/en/zend.mail.read.html
Read messages example from the Zend Framework docs:
$mail = new Zend_Mail_Storage_Pop3(array('host' => 'localhost',
'user' => 'test',
'password' => 'test'));
echo $mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
echo "Mail from '{$message->from}': {$message->subject}\n";
}