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))));
}
Related
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 currently trying to get the UNSEEN/UNREAD messages from my server. Currently, I have this:
$openmail = imap_open($dns, $email, $password) or die("Cannot Connect " . imap_last_error());
if ($openmail) {
/* grab emails */
$emails = imap_search($openmail, 'UNSEEN');
if ($emails) {
//For every e-mail.
$tot = imap_num_msg($openmail);
for ($i = $tot; $i > 0; $i--) {
$structure = imap_fetchstructure($openmail, $i);
if (isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
$message = imap_fetchbody($openmail, $i, 2, FT_PEEK);
if ($part->encoding == 3) {
$message = imap_base64($message);
} else if ($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_qprint($message);
}
}
$header = imap_header($openmail, $i);
$from = imap_utf8($header->fromaddress);
$subject = $header->Subject;
$subject = substr($subject, 0, 150);
$date = $header->Date;
}
/* Print out the Unseen messages in here! */
} else {
/* No unseen messages */
echo "No unseen";
}
}
I've tried sending multiply emails to my mailserver, refreshed the page with the above script. But I keep getting the "No unseen".
I've tried to output the $emails but it's empty. It can't find anything.
If I try to just get ALL the messages (no unseen filter), I can see the emails I've sent to the mailbox, although, they're all marked as read.
Your code $message = imap_fetchbody($openmail, $i, 2, FT_PEEK); uses hardcoded part offsets, i.e. it assumes that a message is always multipart/alternative with text/plain and text/html. That's a very wrong assumption.
You have to look at the output of the BODYSTRUCTURE to see what the MIME structure of your mail is.
With that out of the way, be sure that none of your commands use the BODY fetch operation; you have to use BODY.PEEK. I have no idea how this is accessible within the PHP c-client bindings.
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
Is there any better way to stop spam coming through on my phpmailer script?
Also how would I go about adding formatting to this so its more readable when it gets sent through to email e.g. break lines
I hope my php syntax is correct - as i do not understand PHP.
<?php
# bool has_injection (String $var, [String $var, ...])
function has_injection () {
$values = func_get_args();
for ($i=0, $count=func_num_args(); $i<$count; $i++) {
if ( stristr($values[$i], "%0A") || stristr($values[$i], "%0D") || stristr($values[$i], "\\r") || stristr($values[$i], "\\n")
|| stristr($values[$i], "Bcc") || stristr($values[$i], "Content-Type") ) {
return true;
}
}
return false;
}
$error = '';
if (isset($_POST) && count($_POST)>0) {
# The form has been submitted
$course_title = $_POST['course_title'];
$course_date = $_POST['course_date'];
$course_code = $_POST['course_code'];
$course_fee = $_POST['course_fee'];
$break .= "\n";
$qual_subject_level = $_POST['qual_subject_level'];
$break .= "\n";
$email = $_POST['email'];
if ($name && $email && $subject) {
if (has_injection($name, $email, $subject)) {
# You've got another spammer at work here
$error = 'No spamming';
exit(0);
}
else {
# It's safe to send the message
mail('my#gmail.com',
$subject,
$course_title,
$course_code,
$course_fee,
$break,
$qual_subject_level,
$break,
$subject,
"From: $name <$email>");
}
}
else {
$error = 'Please fill in all the forms';
}
}
?>
One i use is have a text area and use your .css file to display:none it most bots dont read the css and thus think that the text box is shown and if it has content in it it's a bot if it does not then send your email.
E.G CSS
.antiBot{display:none};
HTML
<input type="text" class="antiBot" name="antibot" value="" />
PHP
<?php
if($_REQUEST['antibot'] == ""){
// send your email
}else{
// bot using your system
}
?>
How ever change the name or bot will get be able to notice its a trap and will get around it with little work insted of having to parse the CSS file for your site
So in your case just rap the if above around your code as for formatting of an email if its plain text use dubble quotes and \n (newline) but it wont work in single quotes.