Sent mails with phpmailer don't go to "Sent" IMAP folder - php

in my CRM online system I control ingoing mails with IMAP protocol.
Now I'm making sending mails with phpmailer and SMTP protocol.
Everything is ok but I have one wierd thing. How to make sent with phpmailer script mails go to "Sent" IMAP folder?

There is now a method getSentMIMEMessage in PHPMailer which returns the whole MIME string
$mail = new PHPMailer();
//code to handle phpmailer
$result = $mail->Send();
if ($result) {
$mail_string = $mail->getSentMIMEMessage();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}

I found easier way to do this.
PHPmailer prepares email as string - all You have to do is to put it into right IMAP folder.
I expanded phpmailer class with this code (since vars are protected I can't reach them):
class PHPMailer_mine extends PHPMailer {
public function get_mail_string() {
return $this->MIMEHeader.$this->MIMEBody;
}}
PHP code:
$mail= new PHPMailer_mine();
//code to handle phpmailer
$result=$mail->Send();
if ($result) {
$mail_string=$mail->get_mail_string();
imap_append($ImapStream, $folder, $mail_string, "\\Seen");
}
It works well.

Well, it's pretty difficult, but can be done.
Take a look at the imap-append function.
By being connected to an IMAP stream resource, you can use the imap-append() to append your mails to the Sent folder of your IMAP account.
But reading through the comments will show you that it's a bit tedious to accomplish, but certainly not impossible - you'll probably need to code something on your own, since phpmailer doesn't support this out of the box (and will most likely be too time consuming to implement instead of making something yourself).

You need to be relaying your sent mail through the IMAP host
The IMAP host needs to support the feature (which very few do)
If either of these two points are not true, the short answer is "You can't". In short, really it's down to the mail provider, not your code.
As much as I hate M$, Exchange is one place where they really have got things right - if you are using an Exchange server, all of this is handled for you.

This works well :
Php Manual
if (!$mail->send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
} else{
//echo "Message sent!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
if (save_mail($mail)) {
echo "Message saved!";
}
}
//function
function save_mail($mail)
{
$providerMail = 'Gmail';
$providerMailSentFolder = 'Sent Mail';//You can change 'Sent Mail' to any folder
$providerMailImap = 'imap.gmail.com';//imap.one.com
$path = "{".$providerMailImap.":993/imap/ssl}[".$providerMail."]/".$providerMailSentFolder;
//Tell your server to open an IMAP connection
//using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
}

Related

How Use Sendinblue with PHPMailer

I'm setting up an email configuration with PHPMailer and just work fine with local email in my office, but since I want use Sendinblue as an email API I just stucked and it didn't work.
I tried to find some suggest to fixed it but stucked. Did anyone try to figure out what I'm looking for about Sendinblue with PHPMailer?
With PHPMailer Library in background, I usually use this code to run my program
function send_mail2($from,$from_name,$to,$to_name,$cc,$cc_name,$cc2,$cc_name2,$cc3,$cc_name3,$subjek,$template,$is_smtp,$usermail,$password){
$sendmail = new PHPMailer();
if($is_smtp = 'Y'){
$sendmail->IsSMTP(); // enable SMTP
// $sendmail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$sendmail->SMTPAuth = true; // authentication enabled
$sendmail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$sendmail->Host = "192.x.x.x";
$sendmail->Port = 465; // or 587
$sendmail->Username = "xxx#xxx.com";
$sendmail->Password = "xxx";
}
$sendmail->setFrom("xxx#xxx.com","xxx#xxx.com"); //email pengirim
$sendmail->addReplyTo("xxx#xxx.com","xxx#xxx.com"); //email replay
$sendmail->addAddress($to,$to_name);
$sendmail->AddCC($cc,$cc_name);
$sendmail->AddCC($cc2,$cc_name2);
$sendmail->AddCC($cc3,$cc_name3);
$sendmail->Subject = $subjek;
$sendmail->Body=$template;
$sendmail->isHTML(true);
if(!$sendmail->Send()) {
return "failed";
}else{
return "success";
}
}
I just want to find how to use Sendinblue with PHPMailer.
First of all, it looks like you're using an old version of PHPMailer and have based your code on a very old example, so upgrade.
It doesn't look like you're even trying to use sendinblue; you're pointing your script at a local mail server. Because you're using a literal IP address, SSL will never work because it will fail to verify the certificate.
If you want to use sendinblue directly from PHPMailer, you need to use sendinblue's SMTP servers, and that will be covered in their documentation. If they don't provide an SMTP service (like say mailgun does), you will need to use their HTTP API instead (which has plenty of documentation). You can't use PHPMailer for talking to that, though you can use it for generating messages to send, for example by doing everything as you currently are except don't call send(); do this instead:
$message = $sendmail->getSentMIMEMEssage();
This will give you a fully-formatted RFC822 message ready to submit to an HTTP API.
When you need to configure sendinblue with PHPMailer,
At that time, first, get all configuration detail from your sendinblue account
like Host, Username, Password
And then your PHPMailer use getSentMIMEMEssage(); instend of $mail->isSMTP() or $mail->isMail()
Please check the below screenshot for reference.

E-mail not getting sent in Joomla in combo with VM

I'm new to SO, so bear with me please. I'm fairly noobish regarding code, I'm mostly a webdesigner, not developer. But my own webdeveloper is having a hard time with this problem so I'm trying to find some help where ever I can get.
So, we got this problem on a Virtuemart shop, running version 2.5.23 of Joomla with VM 2.6.10.
Server info:
PHP Built On Linux web04 3.13.0-35-generic #62~precise1-Ubuntu
Database Version: 5.1.73-0ubuntu0.10.04.1-log
Database Collation: utf8_general_ci
PHP Version: 5.3.10-1ubuntu3.14
Web Server: Apache
WebServer to PHP Interface: apache2handler
Joomla! Version: Joomla! 2.5.23 Stable [ Ember ] 24-July-2014 14:00 GMT
So this is not sending mail anywhere. We got it on a testserver and over there, life is good. It's sending e-mail. The testserver is running PHP 5.24.
I've used this to see if this checks out:
<?php
$to = "dontsentmemail#gmail.com";
if( mail( $to , 'This is a test message.' , 'Is this working?' ) ) {
echo 'Email sent.';
} else {
echo 'Email failed to send.';
}
?>
This is working fine. And I'm about to pull out all my hair. We've tried SMTP mail handling, and again, working like a charm on the testserver but it won't work on the live site.
does anybody know if is VM/joomla is using mail() directly or maybe using JUtility::sendMail() as default, and if we can change that, to make it work? Anyone got any ideas?
EDIT
I wasn't aware Joomla already includes its own version of PHPMailer. See Lodder's answer for a better out-of-the-box solution!
Try switching to a specialist mail library, e.g. PHPMailer to send the mail, instead of php's mail function.
I too had a similar problem, emails sent but not delivered, and no bounce messages. PHPMailer managed to send email that also got delivered.
<?php
require_once('path/to/PHPMailerAutoload.php');
//Create a new PHPMailer instance
$mail = new PHPMailer();
// Set PHPMailer to use the sendmail transport
$mail->isSendmail();
// Set who the message is to be sent from
// Name is optional
$mail->setFrom('somebody#yourdomain.com', 'Joe Bloggs');
//Set who the message is to be sent to
// Name is optional
$mail->addAddress('dontsentmemail#gmail.com', 'Jane Bliggs');
//Set the subject line
$mail->Subject = 'Is this working?';
// Set plain text body
$mail->IsHTML(false);
$mail->Body = 'This is a test message.';
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
I would personally use Joomla's built-in JMail class which uses PHPMailer. Have a look at the following:
$mailer = JFactory::getMailer();
$mailer->setSender('dontsentmemail#gmail.com');
$mailer->addRecipient('from#emailaddress.com');
$mailer->setSubject('Your subject');
$body = "Some email text";
$mailer->setBody($body);
$send = $mailer->Send();
if ( $send !== true )
{
echo 'Error sending email';
}
else
{
echo 'Mail sent';
}
You may want to change from#emailaddress.com to whatever suits your needs. There are also some additional features for this class which can be found on the Joomla documentation:
http://docs.joomla.org/Sending_email_from_extensions
Update:
I wasn't aware that you were using a separate PHP file. At the top of your PHP file, you will need to import the Joomla framework like so:
define( '_JEXEC', 1 );
define('JPATH_BASE', __DIR__);
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
$app = JFactory::getApplication('site');
You may need to change the value for JPATH_BASE so that your script points to the root of your Joomla site, relative to where you PHP file is located.
Hope this helps

Send email reliably and handle errors robustly

I'm making my first site for a learning exercise as I've been a java back-end developer. I am setting up a user registration form and since this is going to be my user's first glimpse at my site, I want to make sure I handle things as robustly as possible. Through some trials I've come across and implemented almost all these solutions:
php's mail() function - this worked the first day i tested it and stopped working later. First time I realized sending mail wasn't a "given" simple task
pear mail class - implemented this tonight and is currently still working
pear smtp mail - read about this here. Makes me feel like I should be using smtp?
At this point I have realized sending email reliably is not quite as trivial as I originally thought. My question is what is the most reliable way to send mail, and what is the most robust way to handle exceptions? For instance if SMTP is the most reliable way, please explain why and provide a simple example with error handling.
For any of the errors that occur, are they errors where doing some automated retry would benefit? I understand that just because I send mail doesn't mean the person will get it, but I'm asking what the most robust solution is because I'm sure other people have done this 100 times over.
To prove I'm not just a lazy coder, this is what I've got so far which has been working - but I have no idea how robust this actually is (pear mail):
<?php } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include('Mail.php');
include('Mail/mime.php');
$to = urldecode($_POST['email']);
if (preg_match('(\r|\n)', $to)) {
die('No email injection for you!');
}
$headers = array(
'From'=>'tag <me#mysite.com>',
'Subject'=>'Registration for mysite.com'
);
$text_body = 'boring text message';
$html_body = '<html>
<head><title>Welcome</title></head>
<body>
<p>slightly less boring message</p>
</body>
</html>';
//Utilize the mime class to generate mime body and add mime headers
$mime = new Mail_mime();
$mime->setTXTBody($text_body);
$mime->setHTMLBody($html_body);
$body = $mime->get();
$headers = $mime->headers($headers);
//Utilize the mail class to send the mime mail
$mail = Mail::factory('mail');
$mail->send($to, $headers, $body);
echo 'mail sent maybe?';
?>
EDIT:
Code sample using SMTP with error handling
<?php } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include('Mail.php');
include('Mail/mime.php');
$to = $_POST['email'];
$to = urldecode($to);
if (preg_match('(\r|\n)', $to)) {
die('No email injection for you!');
}
$headers = array(
'From'=>'tag <me#mysite.com>',
'Subject'=>'Registration for mysite.com'
);
$text_body = 'boring text message';
$html_body = '<html>
<head><title>Welcome</title></head>
<body>
<p>slightly less boring message</p>
</body>
</html>';
//Utilize the mime class to generate mime body and add mime headers
$mime = new Mail_mime();
$mime->setTXTBody($text_body);
$mime->setHTMLBody($html_body);
$body = $mime->get();
$headers = $mime->headers($headers);
//Utilize the mail class to send the mime mail
$host = 'mail.mysite.com';
$port = '26';
$username = 'me#mysite.com';
$password ='myPassword';
$smtp = Mail::factory('smtp', array (
'host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
There are typically several steps involved in sending mail:
Application: Put mail into queue of local delivery agent
Delivery agent: Send mail to configured SMTP server
SMTP server: Send mail to destination mail server
User mail application: Fetch mail from mail server
User: Click on mail, read it
PHP's mail() function puts the mail into the queue of the local mail delivery agent on unix. You'll only get an error (return value false) if that does not work. You do not get notified when the agent cannot deliver the mail further or any of the steps 2-5.
Using a direct SMTP connection to your SMTP server at least gives you an if the mail cannot be delivered to your SMTP server, which is more information than you get with mail(). What you don't get is information if the mail does not get read or is simply filtered out into a spam folder, or if the remote mail account does not exist (3-5).
To get to know that the remote account exists, you need to either parse the error response mails ("Undelivered mail returned to sender), or implement the full remote server SMTP connection and sending yourself (step 3), which I would not recommend.
To find out if the mail has been read, you could embed a "web bug", a tiny (potentially clear) image that is displayed in the HTML mail and notifies you that the mail has been displayed. You can use this to put sent mails into a database and mark them as read when your web bug image URL gets called. Mails that did not get read in X days can be seen as "not read" or "failed" - but the user can also simply be on vacation :)
Reliability & robustness
Your own mail server (step 3) automatically tries to re-send mails when the remote user's mail server is down. If that does not work, you'll get mails like "Mail delivery delayed for 24 hours", and another mail when it stopped doing that.
So once the mail is on your mail server, you can be sure that this server will do everything it can to deliver it.

Swift Mailer can address be banned for mass mailing?

I need to send over 2000 mails and I am using Swift Mailer library for it.
We have own server and it has both SMTP and sendmail transports. I am using SMTP:
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
All mails are send fine to few people, but I'm afraid that we will be banned when we send mass mail.
I don't really know what means "banned" and how it looks like, but I'm afraid about the aftermath.
So, is it true, that such "ban" exists and how to implement mass mailing with Swift Mailer in a right way?
P.S.: My code looks like:
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance($message_theme)
->setFrom(array($sender => $name))
->setTo($emails)
->setBody($message_text,"text/html")
;
try {
// Send the message
$result = $mailer->send($message);
}
catch(Exception $e) {
echo "Error: ".$e->getMessage();
}
As I'm hoping you will not use this for spam!!!
Here are some things to do:
try to same different Emails (change name of the recipient in body)
send emails once every 3-4 seconds and not 100 emails/second - it should send 2000 emails in about 2-3 hours.
Blacklisting/graylisting does indeed exist and there are some best practices you can implement to try to avoid these issues. For 2,000 emails, as long as your headers are legitimate, there is nothing fishy going on in your body text, and your recipients are on different domains, you should not run into this issue. However, as khomyakoshka mentions, the above code is incorrect and you should use a loop to send each email. This avoids exposing your entire mail list to each user.
Some additional best practices:
1) Swiftmailer offers plugins (http://swiftmailer.org/docs/plugins.html) that will help you send bulk email. Of particular note are the Throttler and AntiFlood plugins.
2) If you intend on modifying the contents of the mail to tailor to the recipient, consider using the Decorator plugin (also mentioned on the plugins page) for this task.
Hope these tips help.

Two emails when sent via SMTP

I've used two PHP email scripts and routing it through my SMTP server, when I do this though it sends two of the same email.
When I use mail() this doesn't happen, but I'd much rather use SMTP.
Any ideas why this may be occuring?
If you're setting the 'To' and/or 'Recipient' header multiple times, the SMTP server could interpret that as separate e-mail address, thus you'll receive the multiple e-mails.
I'd recommend using the PEAR Mail class. Very simple to use, and handles much of the work for you. It supports multiple backends including SMTP. Likewise, if you want to expand your class to send HTML emails, the Mail_Mime class handles this very nicely, providing methods to set the plain-text body and the HTML body (in case the recipient doesn't support HTML).
So if you're only using PHPMailer without editing it's code, it's not your script's fault. Maybe check your SMTP server's configuration?
function send_email($from, $fromname, $to, $subject, $body, $alt = '')
{
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try
{
$mail->Host = 'localhost'; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
//$mail->AddReplyTo($from, $fromname);
$mail->AddAddress($to);
$mail->SetFrom($from, $fromname);
$mail->Subject = $subject;
//$mail->AltBody = $alt; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->Send();
echo 'Message Sent OK';
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
}
That's the current function so far
Based on your code, if it's the class which is at fault, you'd expect to get 'Message Sent OK' twice (I can't see why that would happen though). If you don't, then I'd be looking at your SMTP server (maybe via a call to support).
I'm assuming you've disabled Reply-to to rule it out as a cause in this case? Note: I'm not suggesting that would affect anything (other than you likely being classified as spam).
Incidentally, I moved from PHPMailer to Swift Mailer some time ago & have never looked back. If you don't get any joy from support then I'd try at least testing with Swift Mailer.
I agree with what da5id said, why dont you take the second error message out. Further have you checked the receiver whether they REALLY get 2 messages?

Categories