Can't send images to gmail through PHPMailer - php

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;
}

Related

gmail api strait forward way to get sender email

I’m having problems getting the sender's email address,
$single_message = $gmail->users_messages->get('me', $msg_id);
"from" usually yields the senders name
To get the email address I have this code
if($partes->getName() == 'Authentication-Results')
{
$outh_res = $partes->getValue();
if(strpos($outh_res, 'smtp.mailfrom=') !== false)
{
$bits = explode('smtp.mailfrom=',$outh_res);
$mail = $bits[1];
if(strpos($mail, ';') !== false)
{
$bits = explode(';',$mail);
$mail = str_replace('"', '',$bits[0]);
}
}
}
That always gives me an email, but when the sender is behind mail chimp (or their own servers (postfix)) for example: bounces+2063633-785c-info=myemail.com#sg1.senderemail.com
In the best case I receive #sendermail.com (from gmail itself I know its info#sendermail.com) so it's useless
In some cases
if($partes->getName() == 'Reply-To')
{
$other_mail = str_replace('"', '',$partes->getValue());
}
Gives me a helpful email others just the senders name
as suggested in github php gmail api issue # 521 and other places
$only_header = $gmail->users_messages->get('me',$msg_id, ['format' => 'metadata', 'metadataHeaders' => ['To','X-Original-To','X-Original-From','From','Reply-To','Subject']]);
It gives exactly the same info.
Is there any way that the api gives me exactly the sender email address even if it's behind mail chimp or other 3rd party sender?
There's a similar answer Get sender email from gmail-api, I already loop the headers and tried zingzinco's answer.
Edit: Thanks to Joey Tawadrous;
Php code:
if($partes->getName() == 'From')
{
$raw_from = $partes->getValue();
if(strpos($raw_from, '<') !== false)
{
$bit = explode('<',$raw_from);
$bit2 = explode('>',$bit[1]);
$final_email = $bit2[0];
$sender_name = str_replace('"', '',$bit[0]);
}
else
{
$sender_name = limpiarm(str_replace('"', '',$raw_from));
}
}
var email = '';
var messageFrom = _.where(message.payload.headers, {name: 'From'})[0].value;
if(messageFrom.includes('<')) {
var fromObj = messageFrom.split('<');
email = fromObj[1];
fromObj = email.split('>');
email = fromObj[0];
}
return email;

Laravel Mail send even if cc and bcc is null

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"]);
}

cryptic mail body when using imap_fetchbody

I am using following code to exctract among others the mail body of mails.
$imap = imap_open($mailbox,$user,$password);
$mails = imap_search($imap,'UNSEEN');
foreach($mails as $mail)
{
$message = trim(utf8_encode(quoted_printable_decode(imap_fetchbody($imap,$mail,"1"))));
if(strpos($message,"<html") !== false)
{
$mail_body = fopen($dir."mail.html","w");
}
else
{
$mail_body = fopen($dir."mail.txt","w");
}
}
This is working fine and it works with every test I did.
html-mails, plain-text-mails, also if the mails are forwarded.
Now from some other source I get mails, where the message (after using imap_fetchbody) just looks like some crypted string. Like this:
dGVpZW4gaW0gUERGLUZvcm1hdDoNClJla2xhbWF0aW9uc2luZm9ybWF0aW9uOiAyMTMzNjc0MSBS
SV8yMTMzNjc0MS5wZGYNCg0KTWl0IGZyZXVuZGxpY2hlbiBHcsO8w59lbg0KSWhyIG5vYmlsaWEg
VGVhbQ0KX19fDQoNCm5vYmlsaWEtV2Vya2UgSi4gU3RpY2tsaW5nIEdtYkggJiBDby4gS0cgfCBX
YWxkc3RyLiA1My01NyB8IDMzNDE1IFZlcmwNCg0KRGllIEdlc2VsbHNjaGFmdCBpc3QgZWluZSBL
I already tried to use some other arguments for imap_fetchbody like "1.1" or "1.2", but when I do that the message is empty.
Do you have any idea why this effect occurs?
I finally found a solution. The cause seems to be forwarded mails, that were initially sent from an apple device.
Now I use this to extract the message and it works.
$structure = imap_fetchstructure($imap, $mail);
$part = $structure->parts[1];
$message = imap_fetchbody($imap,$mail,1);
if(strpos($message,"<html") !== false)
{
$message = trim(utf8_encode(quoted_printable_decode($message)));
}
else if($part->encoding == 3)
{
$message = imap_base64($message);
}
else if($part->encoding == 2)
{
$message = imap_binary($message);
}
else if($part->encoding == 1)
{
$message = imap_8bit($message);
}
else
{
$message = trim(utf8_encode(quoted_printable_decode(imap_qprint($message))));
}

Symfony 3 - Swift_Mailer - Send email but make failures and return 0

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

wp_mail returns true but not receiving mails

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

Categories