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
Related
use PHPMailer\PHPMailer\PHPMailer;
use Aws\Ses\SesClient;
use Aws\Ses\Exception\SesException;
require 'vendor/autoload.php';
if(!function_exists("sendmailalexraw")){
function sendmailalexraw($email,$subject,$messages,$definesender)
{
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
$sender = $definesender;
$sendername = 'Alex';
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
$recipient = $email;
// Specify a configuration set.
$configset = 'ConfigSet';
// Replace us-west-2 with the AWS Region you're using for Amazon SES.
$region = 'eu-west-1';
$subject = $subject;
$htmlbody = <<<EOD
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please see the attached file for a list of customers to contact.</p>
</body>
</html>
EOD;
$textbody = <<<EOD
Hello,
Please see the attached file for a list of customers to contact.
EOD;
//// The full path to the file that will be attached to the email.
$att = 'path/to/customers-to-contact.xlsx';
// Create an SesClient.
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => $region
));
// Create a new PHPMailer object.
$mail = new PHPMailer;
// Add components to the email.
$mail->setFrom($sender, $sendername);
$mail->addAddress($recipient);
$mail->Subject = $subject;
$mail->Body = $htmlbody;
$mail->AltBody = $textbody;
$mail->addAttachment($att);
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configset);
// Attempt to assemble the above components into a MIME message.
if (!$mail->preSend()) {
echo $mail->ErrorInfo;
} else {
// Create a new variable that contains the MIME message.
$message = $mail->getSentMIMEMessage();
}
// Try to send the message.
try {
$result = $client->sendRawEmail([
'RawMessage' => [
'Data' => $messages
]
]);
// If the message was sent, show the message ID.
$messageId = $result->get('MessageId');
echo("Email sent! Message ID: $messageId"."\n");
} catch (SesException $error) {
// If the message was not sent, show a message explaining what went wrong.
echo("The email was not sent. Error message: "
.$error->getAwsErrorMessage()."\n");
}
}
}
$email='example#gmail.com';
$subject='abc';
$messages='xyz';
$definesender='info#verifieddomain.net';
sendmailalexraw($email,$subject,$messages,$definesender);
?>
I am trying to send RawMessage with Amazon SES but I get :
The email was not sent. Error message: Missing required header 'From'.
Sender I use it's verified, my Amazon SES it's active (out of sendbox ) .
I am needing to send as RAW Message to create unsubscribe option for emails I am sening. As I read from documentation it have to be raw email to be able to add this parameters.Thank you !
You have to base64 encode the message :
$result = $client->sendRawEmail([
'RawMessage' => [
'Data' => base64_encode($messages)
]
]);
Since you're using AWS Ses, you could do it this way:
define('SENDER', 'Your name<a#a.com>');
define('RECIPIENT', 'b#b.com');
define('CCLIST', 'c#c.com');
define('REGION','your region');
define('SUBJECT','Your subject goes here');
$bodytext = "<h2>Your body goes here.</h2>" . PHP_EOL;
$bodytext .= "<p>Append as many rows as you want</p>";
define('BODY',$bodytext);
$client = SesClient::factory(array(
'version'=> 'latest',
'region' => 'your region'
));
$request = array();
$request['Source'] = SENDER;
$request['Destination']['ToAddresses'] = array(RECIPIENT);
$request['Destination']['CcAddresses'] = array(CCLIST);
$request['Message']['Subject']['Data'] = SUBJECT;
$request['Message']['Body']['Html']['Data'] = BODY;
try {
$result = $client->sendEmail($request);
$messageId = $result->get('MessageId');
echo("Email successfully sent! Message ID: $messageId"."\n");
} catch (Exception $e) {
echo("The email was not sent. Error message: ");
echo($e->getMessage()."\n");
}
I'm trying to send out E-mails using a PowerShell script, my company's Virus scan (McAfee) is blocking port 25. I know that I can go into McAfee's setting and uncheck the "prevent mass E-mail.. option", I also know that I can call Outlook within my script to send E-mail while user is logged in (which is too intrusive). My question is, is there any other way to send e-mails using PowerShell without using any of the options I mentioned above.
Thank you.
$From = "name#name.com"
$To = "name#name.com"
$Body = Test"
$Subject2 = "Hi"
$SMTPServer ="smtp.com"
Send-MailMessage -From $From -To $To -SmtpServer $SMTPServer -Subject $Subject1 -Body $Body'
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "name#name.com"
$Mail.Subject = "Hi"
$Mail.Body = "Hello"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Mail.Send() '
Use .NET classes
You could create a [MailMessage] object manually and send it with the [SmtpClient] class, but this may fall foul of the McAfee software in the same way that Send-MailMessage does.
$From = "name#name.com"
$To = "name#name.com"
$Body = "Test"
$Subject2 = "Hi"
$SMTPServer ="smtp.com"
$message = New-Object System.Net.Mail.MailMessage $From, $To
$message.Subject = $Subject2
$message.Body = $Body
$smtpclient = New-Object Net.Mail.SmtpClient($SMTPServer)
$smtpclient.Send($message)
http://exchangeserverpro.com/powershell-send-html-email/
Use Exchange Web Services
In order to use EWS you will need the Microsoft.Exchange.WebServices.dll file, which you may find somewhere such as the following:
C:\Program Files\Microsoft\Exchange\Web Services\1.0
C:\Program Files\Microsoft\Exchange\Web Services\2.2
Download from Microsoft
An example function implementation of this from Mike Pfeiffer's blog is here (and linked below):
Function Send-EWSMailMessage {
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipelineByPropertyName=$true, Mandatory=$true)]
[Object]
$PrimarySmtpAddress,
[Parameter(Position=1, Mandatory=$true)]
[System.String]
$Subject,
[Parameter(Position=2, Mandatory=$true)]
[System.String]
$Body
)
BEGIN {
Add-Type -Path "C:\bin\Microsoft.Exchange.WebServices.dll"
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$user = [ADSI]"LDAP://<SID=$sid>"
}
PROCESS {
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.AutodiscoverUrl($user.Properties.mail)
if($PrimarySmtpAddress -is [Microsoft.Exchange.Data.SmtpAddress]) {
$Recipient = $PrimarySmtpAddress.ToString()
} else {
$Recipient = $PrimarySmtpAddress
}
$mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
$mail.Subject = $Subject
$mail.Body = $Body
[Void]$mail.ToRecipients.Add($Recipient)
$mail.SendAndSaveCopy()
}
END {
}
}
Sending Email with PowerShell and the EWS Managed API
The following link may be useful, but isn't specifically aimed at PowerShell implementations:
Creating and sending email messages by using the EWS Managed API 2.0
Does the SMTP server you are using support encrypted connection ? If so try:
Send-MailMessage -To $to -From $from -SmtpServer $smtp -UseSsl -Port "587"
I would test it but I don't have McAfee.
I'm using Swift Mailer v3.3.2 to send emails from my app and I need to be able to change the text of the sender.
My code looks like this:
//Sending email
$swift = email::connect();
$email_message = new View('email/email_template');
$subject = "Subject here";
$from = "subdomain#domain.org";
$email_message->content_email = new View('email/content/signup');
$email_message->content_email->user = $user;
$message = $email_message;
$recipients = new Swift_RecipientList;
$recipients->addTo($user->email);
// Build the HTML message
$message = new Swift_Message($subject, $message, "text/html");
if ($swift->send($message, $recipients, $from)) {
;
} else {
;
}
$swift->disconnect();
I want to be able to set the name text of the sender as 'Senders_Name Senders_Surname', even though the sender is still subdomain#domain.org
Any clue on how to do that?
After line
$message = new Swift_Message($subject, $message, "text/html");
you should add
$message->setFrom(new Swift_Address($from , 'Senders_Name Senders_Surname'));
The whole working script below (I've just tested it in 3.3.2 version):
<?php
require ('lib/Swift.php');
require('lib/Swift/Connection/SMTP.php') ;
$smtp = new Swift_Connection_SMTP();
$smtp->setServer('server');
$smtp->setUsername('username');
$smtp->setPassword('password');
$smtp->setEncryption($smtp::ENC_SSL);
$smtp->setPort(465);
$swift = new Swift($smtp);
$swift->connect();
$subject = "Subject here";
$from = 'test#email.com';
$message = 'test message';
$recipients = new Swift_RecipientList;
$recipients->addTo('mymail');
// Build the HTML message
$message = new Swift_Message($subject, $message, "text/html");
$message->setFrom(new Swift_Address($from , 'Senders_Name Senders_Surname'));
if ($swift->send($message, $recipients, $from)) {
;
} else {
;
}
$swift->disconnect();
Below image how the sender is displayed in email client (Thunderbird for me) so it works fine. If you test it in your email client make sure you don't have account from set as one of your mail accounts. In that case email client shows for example "Me" or sth else. The best for test just fill in addTo with your email and smtp settings and leave from and other parts unchanged
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";
}
Is there any reason why phpmailer will send emails with empty body on a remote server but works fine on a local server?
The code is the same
$res = $db->run("SELECT * FROM email WHERE code = 'welcome'");
$m = $res[0];
$body = nl2br($m['content']);
$body = str_replace("[EMAIL]", $ld['email'], $body);
$body = str_replace("[PASSWORD]", $ld['password'], $body);
$mail = new PHPMailer();
$mail->AddReplyTo($m['from_address'], $m['from_name']);
$mail->AddAddress($ld['email'], "");
$mail->SetFrom($m['from_address'], $m['from_name']);
$mail->Subject = $m['subject'];
$mail->AltBody = strip_tags($body);
$mail->MsgHTML($body);
if ($mail->Send() === false)
{
p($mail->ErrorInfo);
}
unset($mail);
If anybody finds this and has no clue just like me, an update to phpmailer 5.2.6 will fix this.