Skip to content

Instantly share code, notes, and snippets.

@Radon8472
Forked from DavidRockin/Mailer.php
Created November 15, 2019 11:52
Show Gist options
  • Save Radon8472/388be692bfeaf274e1ff53d7f266bdce to your computer and use it in GitHub Desktop.
Save Radon8472/388be692bfeaf274e1ff53d7f266bdce to your computer and use it in GitHub Desktop.
PHPMailer save emails to IMAP folder
<?php
include("Mailer.php");
$mail = new Mailer();
$mail->isSMTP(); // Tell PHPMailer we're going to use SMTP
$mail->Host = 'mail.localhost'; // Set SMTP host
$mail->Username = 'noreply@localhost'; // Set the our email address
$mail->Password = 'YourPassword'; // Set email address password
$mail->From = "[email protected]"; // The sender's email
$mail->FromName = "John Doe"; // The sender's name
$mail->addAddress("recipient@localhost"); // Recipient's email
$mail->addReplyTo($mail->From, $mail->FromName); // Add a reply to
$mail->Subject = "Mail for you!"; // Message subject
$mail->Body = "Your message contents..."; // Message contents
if($mail->send()) { // Attempt to send the email
$mail->copyToFolder(); // Will save into inbox
$mail->copyToFolder("Sent"); // Will save into Sent folder
} else {
echo "An error occurred, failed to send the email";
}
<?php
class Mailer extends PHPMailer {
/**
* Save email to a folder (via IMAP)
*
* This function will open an IMAP stream using the email
* credentials previously specified, and will save the email
* to a specified folder. Parameter is the folder name (ie, Sent)
* if nothing was specified it will be saved in the inbox.
*
* @author David Tkachuk <http://davidrockin.com/>
*/
public function copyToFolder($folderPath = null) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{" . $this->Host . "}" . $path , $this->Username, $this->Password);
imap_append($imapStream, "{" . $this->Host . "}" . $path, $message);
imap_close($imapStream);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment