I have mail send function in laravel
public static function Compose($to,$cc,$bcc,$subject,$body)
{
// return $to;
try
{
$data = [
'body' => $body
];
if(env('APP_ENV') == "local")
{
$email["subject"] = $subject;
$email["to"] = $to;
$email["cc"] = $cc;
$email["bcc"] = $bcc;
Mail::send('email.composeMail', $data, function ($message) use ($email) {
$message
->subject($email["subject"])
->to($email["to"]);
->cc($email["cc"]);
->bcc($email["bcc"]);
});
}
else
{
$email["subject"] = $subject;
$email["to"] = $to;
$email["cc"] = $cc;
$email["bcc"] = $bcc;
Mail::send('email.composeMail', $data, function ($message) use ($email) {
$message
->subject($email["subject"])
->to($email["to"]);
->cc($email["cc"]);
->bcc($email["bcc"]);
});
}
}
catch (\Exception $e)
{
Log::critical('Critical error occurred upon processing the transaction in Email.php -> Email class -> RevertPropertyToInbox method');
throw new CustomErrorHandler($e->getMessage(),Constant::LogLevelCritical);
}
}
In many cases CC and BCC is Null.
But mails aren't sent and I am getting error message
Here , I want to use code as it is without checking if CC or BCC is null, Is there any thing missed by me so that I can achieve what I am planning to .
Those methods can all be called with an array instead of a plain string (docs). In that case, you should be able to just leave the array empty. Try this:
$message
->subject($email["subject"])
->to($email["to"]);
->cc($email["cc"] ?: []);
->bcc($email["bcc"] ?: []);
you cannot send email if the email address is blank, it will always throw error
instead you need to check and then send email accordingly
try this
if($email["cc"] =='' && $email["bcc"] == ''){
$message
->subject($email["subject"])
->to($email["to"]);
}
elseif($email["cc"] ==''){
$message
->subject($email["subject"])
->to($email["to"])
->bcc($email["bcc"]);
}
else{
$message
->subject($email["subject"])
->to($email["to"])
->cc($email["cc"]);
}
Related
I'm using PHPMailer to send some messages in my intranet, the problem occurs when I try to send images in the body of the email, if I just send the images as an attachment everything goes smoothly, but when I try to send the images in the body of the mail Gmail (and just Gmail) ignores the image, even though it shows the message.
The one in the right is gmail, and the blacked out thing is the company logo, added through the AddEmbeddedImage() function
Even stranger is that I send an embedded image to header of the mail, and this one shows normally.
What can I do so that the images appear?
This is the code:
public function enviaEmail($email = "", $subject, $body, $nomes_anexos, $tipo_noticia = false) {
global $config;
if($tipo_noticia && ($tipo_noticia == 'company' || $tipo_noticia == 'company')){
$this->mail->FromName = $config['email_fromname_company'];
} else {
$this->mail->FromName = $config['email_fromname'];
}
$this->mail->From = $config['email_from'];
$header = $this->includeHeader($subject);
$footer = $this->includeFooter();
if(empty($email)){
$this->logger->log("Email em branco.");
return false;
}
$this->mail->ClearAllRecipients();
$this->mail->AddAddress($email);
$this->mail->Subject = $subject;
$this->mail->Body = $header.$body.$footer;
$this->mail->AltBody = strip_tags($body).$footer;
//THIS WORKS
if($tipo_noticia && ($tipo_noticia == 'company' || $tipo_noticia == 'mensagem_company')){
$this->mail->AddEmbeddedImage(dirname(__FILE__).'/../../public/img/company.png', 'logo', 'company.png');
} else {
$this->mail->AddEmbeddedImage(dirname(__FILE__).'/../../public/img/logo_local_novo.png', 'logo', 'local.png');
}
if(!empty($nomes_anexos)){
foreach($nomes_anexos as $an){
$nome_anexo_final = preg_replace("/^(.*)?-/","", $an);
$this->mail->AddAttachment(PATH_ANEXOS."/".$an, urldecode($nome_anexo_final));
}
}
if(!$this->mail->Send()) {
$this->logger->log("Erro ao enviar e-mail '$subject' para '$email': ". $this->mail->ErrorInfo);
return false;
}
return true;
}
I'm working on editing a site which has been built using some strange Smarty system, template TPL files and a load of JS and PHP.
I have a Classes in PHP files which sends and email to an array of email address from a differnt PHP file.
I'm wanted to add to this array so it sends a copy of the email to the person who filled in the form.
The array of recipents is:
//target email address settings
$this->settings['mailer_address_booknow'] = array('ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'james#bernhardmedia.com');
And the sending PHP file is:
public function SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message ) {
$smartyObj = Configurator::getInstance()->smarty;
$send_message = '';
$send_result = 0;
try {
$mail = new PHPMailer( true );
$mail->IsSMTP( true );
$mail->SMTPDebug = false;
$mail->IsHTML( true );
$mail->Host = Configurator::getInstance()->getSettings( "phpmailer_smtp" );
$mail->ClearAddresses();
for( $x = 0;$x < sizeof($email_address_array);$x++ ){
$mail->AddAddress( trim($email_address_array[$x]) );
}
$smartyObj->assign( 'email_data', $email_data );
$mail->SetFrom( 'info#forexchange.co.uk', 'Forexchange Currency Order');
$mail->Subject = $subject;
$mail->Body = $smartyObj->fetch( $template );
if(!$mail->Send()) {
} else {
$send_result = 1;
}
} catch (phpmailerException $e) {
$send_message = $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$send_message = $e->getMessage(); //Boring error messages from anything else!
}
//echo $send_result;
//exit;
return $send_result;
}
The form is on the home page of this site - http://www.forexchange.co.uk/
Please help, I'm stumped!
Smarty I think refers to the Smarty template Engine for php see here
Append the email address to the array $email_address_array
When you call the method
SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message );
either append the email to that data set ($email_address_array) before you call it or append it inline ( in the call)
Can you show how you call it?
EDIT
If your data is stored in
$this->settings['mailer_address_booknow'];
add that to the call,
SendEmail( $this->settings['mailer_address_booknow'] , $email_data, $subject, $template, &$send_message );
if you need to add to that array then do this before calling it
$this->settings['mailer_address_booknow'] = "ADDED_EMAIL";
I have a development that makes use of SwiftMailer to send Emails.
I have a Development server where it is working perfectly (with PHP 5)
And I have a production server where there is PHP 7 (and the server is very virgin, with little configuration) where it is giving these problems
The emails are sent perfectly but the mailer returns 0.
My email sending function is this:
public function sendEmail ($email) {
$transport = \Swift_MailTransport::newInstance("localhost", 25);
$mailer = \Swift_Mailer::newInstance($transport);
$message = \Swift_Message::newInstance("Recuperación de Contraseña");
if (isset($email["subject"]) && !empty($email["subject"])) {
$message->setSubject($email["subject"]);
}
if (isset($email["from"]) && !empty($email["from"])) {
$message->setFrom($email["from"]);
}
if (isset($email["to"]) && !empty($email["to"])) {
$message->setTo($email["to"]);
$message->setReadReceiptTo($email["to"]);
}
if (isset($email["embed_images"]) && !empty($email["embed_images"])) {
foreach ($email["embed_images"] as $embedImage_key=>$embedImage_value) {
if (!empty($embedImage_value)) {
$email["embed_images"][$embedImage_key] = $message->embed(\Swift_Image::fromPath($embedImage_value));
}
}
}
$email["parameters"] = array_merge($email["parameters"], array("embed_images" => $email["embed_images"]));
if (!isset($email["body"]) || empty($email["body"])) {
$message->setBody(
$this->renderView(
$email["template"],
$email["parameters"]
), 'text/html'
);
}
if (isset($email["attach_images"]) && !empty($email["attach_images"])) {
foreach ($email["attach_images"] as $attachImage_key=>$attachImage_value) {
if (!empty($attachImage_value)) {
$message->attach(Swift_Attachment::fromPath($attachImage_value));
}
}
}
$statusSend = true;
$logger = new \Swift_Plugins_Loggers_ArrayLogger;
//$logger = new \Swift_Plugins_Loggers_EchoLogger; //echo messages in real-time
$mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
if (!$mailer->send($message, $failures)) {
$statusSend = false;
echo "Failures:";
print_r($failures);
}
echo $logger->dump(); //not needed if using EchoLogger plugin
return $statusSend;
}
And passes through
if (!$mailer->send($message, $failures)) {
Is Swift_Mailer's problem? From PHP?
Thanks
I have the following script that checks emails and do something with them if they are correct formatted.. I am using FILTER_VALIDATE_EMAIL for this
Here is the code:
if(!empty($_POST['maillist'])){
$_POST['maillist'] = 'mariatettamanti#gmail.com,
H0889#sofiaertel.com,sdfd#sfs.com,';
$mails = explode(',',$_POST['maillist']);
foreach($mails as $mail){
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail." - Invalid email format<br />";
}else{
echo 'do job with this mail';
}
}
}
As you can see mails are formatted as mails but the function prints only first mail as correct and the rest as wrong.. Why is that? What am I missing? Thanks
Problem is with last comma in your email address. It create and empty value at the end . To avoid this you use isset()
if (!empty($_POST['maillist'])) {
$_POST['maillist'] = 'H0889#sofisadatel.com,info#daddsadyomiaasdmi.com,info#hotsdaelmidasami.com,';
$mails = explode(',', $_POST['maillist']);
foreach ($mails as $mail) {
if (isset($mail) && $mail != "") {// check for empty email
if(!filter_var(trim($mail), FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail . " - Invalid email format<br />";
} else {
echo 'do job with this mail';
}
}
}
}
I am using wp_mail() to receive mails which is submitted through a contact form in my wordpress blog. wp_mail() returns true but the thing is i am not receiving any mails. I have also tried to change the mail address to hotmail from gmail but no luck.
Ajax code in my contact template
$('#send').click(function() {
//For Validation
function validateText(name) {
var pattern = /^[a-zA-Z'-.\s]+$/;
if (pattern.test(name)) {
return true;
}
return false;
}
//For Validation
function validateMail(mail) {
var pattern = /^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,3}$/;
//var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if (pattern.test(mail)) {
return true;
}
return false;
}
//Getting values from the form
var name = $('#name').val(), mail = $('#mailid').val(), query = $('#message').val(), error = 1;
//For Validation
if(name == "" || !(validateText(name))) {
$('#name').addClass('error');
error = 0;
}
////For Validation
if(mail == "" || !(validateMail(mail))) {
$('#mailid').addClass('error');
error = 0;
}
//For Validation
if(query == "") {
$('#message').addClass('error');
error = 0;
}
if(!error) { // If validation fails
return false;
}
$('#sendAlert').show();
$('#send').html('Sending...');
$.post(ajax_object.ajaxurl, { // Using ajax post method to send data
action: 'ajax_action',
sendmail: 'nothing',
name: name,
mail: mail,
query: query
}, function(data) {
$('#send').html('Send');
alert(data); // Alerting response
return false;
});
});
In Functions.php
function ajax_action_stuff() {
if(isset($_POST['sendmail'])) {
function set_html_content_type()
{
return 'text/html';
}
if(isset($_POST['name']) && isset($_POST['mail']) && isset($_POST['query'])) {
$name = $_POST['name'];
$email = $_POST['mail'];
$query = $_POST['query'];
$to = 'vigneshmoha#gmail.com';
if($name == "" || $email == "" || $query == "") {
echo "Fail";
return false;
}
$subject = "Website - Query from ".$name;
$message = "Hi,
<p><strong>Name</strong>:".$name."</p>
<p><strong>Mail</strong>:".$email."</p>
<h3><strong>Query</h3>
<p>".$query."</p>";
$headers[] = 'From: no-reply#gmail.com'."\r\n";
$headers[] = '';
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
$mailsent = wp_mail( $to, $subject, $message, $headers);
remove_filter( 'wp_mail_content_type', 'set_html_content_type' ); // reset content-type to to avoid conflicts -- http://core.trac.wordpress.org/ticket/23578
if($mailsent) {
echo $to;
} else {
echo 'error';
}
} else {
echo 'error';
}
} else {
echo 'error';
}
die();
}
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' );
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_stuff' );
There is a possibility that your email is being marked as spam, or it's simply your email provider is not allowing it to reach your inbox, are you sending via SMTP?
Do you have SPF records setup? If you are sending an email from your website, and have the from header set as #gmail.com or #hotmail.com, this will surely not arrive in your inbox as the email is not originating from the gmail or hotmail servers, it's coming from yours, so it think's you are trying some phishing attack.
Edit:
No, Its not marked as spam. I have checked the spam too. Mail is not
receiving at all. wp_mail() should returns true once it has sent the
mail right? So Should i change the from header to something else?
-vigneshmoha
That means the mail has left your server, it doesn't mean it'll arrive in your inbox, as there are many other steps between your server and your inbox, and a few different things could of went wrong in this process. Try testing out the From: header, change to example#yourdomainname.com