I am having problems sending emails using the PHPMailer class for my registration form. I was wondering if the below code could be changed into a normal Mail class please.
<?php
require_once('PHPMailer_v5.1/PHPMailer.php');
class Email {
public $objUrl;
private $objMailer;
public function __construct($objUrl = null) {
$this->objUrl = is_object($objUrl) ? $objUrl : new Url();
$this->objMailer = new PHPMailer();
$this->objMailer->IsSMTP();
$this->objMailer->SMTPAuth = true;
$this->objMailer->SMTPKeepAlive = true;
$this->objMailer->SMTPSecure = 'ssl';
$this->objMailer->Host = "smtp.gmail.com";
$this->objMailer->Port = 465;
$this->objMailer->Username = "email here";
$this->objMailer->Password = "password here";
$this->objMailer->SetFrom("email here", "name here");
$this->objMailer->AddReplyTo("email here ", "name here");
}
public function process($case = null, $array = null) {
if (!empty($case)) {
switch($case) {
case 1:
// add url to the array
$link = "<a href=\"";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "\">";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "</a>";
$array['link'] = $link;
$this->objMailer->Subject = "Activate your account";
$this->objMailer->MsgHTML($this->fetchEmail($case, $array));
$this->objMailer->AddAddress(
$array['email'],
$array['first_name'].' '.$array['last_name']
);
break;
}
// send email
if ($this->objMailer->Send()) {
$this->objMailer->ClearAddresses();
return true;
}
return false;
}
}
public function fetchEmail($case = null, $array = null) {
if (!empty($case)) {
if (!empty($array)) {
foreach($array as $key => $value) {
${$key} = $value;
}
}
ob_start();
require_once(EMAILS_PATH.DS.$case.".php");
$out = ob_get_clean();
return $this->wrapEmail($out);
}
}
public function wrapEmail($content = null) {
if (!empty($content)) {
return "<div style=\"font-family:Arial,Verdana,Sans-serif;font-size:12px;color:#333;line-height:21px;\">{$content}</div>";
}
}
}
Any help is much appreciated
Thanks
I have tried to amend the code to the below code but all I get is a blank screen. I have checked on firefox and no error messages are displayed. Can anyone help fix the problem.
Thank you
<?php
//require_once('PHPMailer_v5.1/PHPMailer.php');
class Email {
public $objUrl;
//private $objMailer;
public function __construct($objUrl = null) {
$this->objUrl = is_object($objUrl) ? $objUrl : new Url();
$to = "qakbar26#gmail.com";
$headers = 'MIME-Version: 1.0'."\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
$headers .= "From: qakbar26#gmail.com";
}
public function process($case = null, $array = null) {
if (!empty($case)) {
switch($case) {
case 1:
// add url to the array
$link = "<a href=\"";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "\">";
$link .= SITE_URL.$this->objUrl->href('activate', array('code', $array['hash']));
$link .= "</a>";
$array['link'] = $link;
$subject = "Activate your account";
$message($this->fetchEmail($case, $array));
$address(
$array['email'],
$array['first_name'].' '.$array['last_name']
);
break;
}
// send email
if ($send()) {
$this->ClearAddresses();
return true;
}
return false;
}
}
public function fetchEmail($case = null, $array = null) {
if (!empty($case)) {
if (!empty($array)) {
foreach($array as $key => $value) {
${$key} = $value;
}
}
ob_start();
require_once(EMAILS_PATH.DS.$case.".php");
$out = ob_get_clean();
return $this->wrapEmail($out);
}
}
public function wrapEmail($content = null) {
if (!empty($content)) {
return "<div style=\"font-family:Arial,Verdana,Sans-serif;font-size:12px;color:#333;line-height:21px;\">{$content}</div>";
}
}
}
Just an update I have manged to get the PHPMailer ot work after I commented out the below line of code.
$this->objMailer->IsSMTP();
Not sure why but the IsSMTP(); is not letting the emails go through.
Related
I'm retrieving Gmail e-mails through IMAP. I'm setting the FT_PEEK option wherever I can, and finally, I've even opened the mailbox as read-only (OP_READONLY). Yet, my code is marking the messages as read.
Here is the code:
class imap{
CONST HOSTNAME='{imap.gmail.com:993/imap/ssl}INBOX';
CONST USERNAME = '[Address hidden]';
CONST PASSWORD = '[Password hidden]'; //App password from Google
function getMessagesSince($date){
//This will return a collection of email objects.
$messages=array();
if(!$imap=imap_open($this::HOSTNAME, $this::USERNAME, $this::PASSWORD, OP_READONLY)) throw new exception("Unable to connect to IMAP mailbox. ".imap_last_error());
$since=date_format($date, 'j F Y');
$emails=imap_search($imap, 'SINCE "'.$since.'"', SE_UID|FT_PEEK);
foreach($emails as $email){
$messages[]=$this->getMessage($email, $imap);
}
imap_close($imap);
return $messages;
}
private function getMessage($uid, $imap){
//First get the headers
$headers=$this->getHeaders($uid, $imap);
$datereceived=date('Y-m-d H:i:s', strtotime($headers->date));
$sender=$headers->from[0]->mailbox."#".$headers->from[0]->host;
$cc=$headers->cc;
$subject=$headers->subject;
//Now get the message body
$message=$this->getBody($uid, $imap);
$email=new email();
$email->uid=$uid;
$email->datereceived=$datereceived;
$email->sender=$sender;
$email->cc=$cc;
$email->subject=$subject;
$email->message=$message;
return $email;
}
private function getHeaders($uid, $imap){
//Return an array of headers for the referenced message
//$overview = imap_fetch_overview($imap, $uid, FT_UID); //As we used the SE_UID flag when searching, we have to use it when fetching.
//We use this, rather than fetch_overview, because the overview doesn't have the cc information.
$hText = imap_fetchbody($imap, $uid, '0', FT_UID|FT_PEEK);
$headers = imap_rfc822_parse_headers($hText);
return $headers;
}
private function getBody($uid, $imap){
$body = $this->get_part($imap, $uid, "TEXT/HTML");
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($imap, $uid, "TEXT/PLAIN");
}
return $body;
}
private function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false){
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID|FT_PEEK);
switch ($structure->encoding) {
case 3:
return imap_base64($text);
case 4:
return imap_qprint($text);
default:
return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
private function get_mime_type($structure){
$primaryMimetype = ["TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"];
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
}
Can anyone spot something I'm missing?
(This is just some extra text, because it's saying that the post is mostly code. I'm just typing here until it lets me post.)
You should delete OP_READONLY flag from imap_open() .
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have created a registration form and it works my only issues is I want to be able to hide the post info in the url if you click submit and the validation fails it does this
register.php?action=signup
is there a mod rewrite for this?
so that the url remains
register.php
removing the ?action=signup
I have searched every where but have came up with nothing
php code for register page
<?php
//Error reporting #1-8F636958
error_reporting(E_ALL | E_STRICT);
//End Error reporting
//Include Common Files #1-EDC1CE42
define("RelativePath", ".");
define("PathToCurrentPage", "/");
define("FileName", "NewPage1.php");
include_once(RelativePath . "/Common.php");
include_once(RelativePath . "/Template.php");
include_once(RelativePath . "/Sorter.php");
include_once(RelativePath . "/Navigator.php");
//End Include Common Files
class clsRecordusers { //users Class #2-9BE1AF6F
//Variables #2-9E315808
// Public variables
public $ComponentType = "Record";
public $ComponentName;
public $Parent;
public $HTMLFormAction;
public $PressedButton;
public $Errors;
public $ErrorBlock;
public $FormSubmitted;
public $FormEnctype;
public $Visible;
public $IsEmpty;
public $CCSEvents = "";
public $CCSEventResult;
public $RelativePath = "";
public $InsertAllowed = false;
public $UpdateAllowed = false;
public $DeleteAllowed = false;
public $ReadAllowed = false;
public $EditMode = false;
public $ds;
public $DataSource;
public $ValidatingControls;
public $Controls;
public $Attributes;
// Class variables
//End Variables
//Class_Initialize Event #2-627C035C
function clsRecordusers($RelativePath, & $Parent)
{
global $FileName;
global $CCSLocales;
global $DefaultDateFormat;
$this->Visible = true;
$this->Parent = & $Parent;
$this->RelativePath = $RelativePath;
$this->Errors = new clsErrors();
$this->ErrorBlock = "Record users/Error";
$this->DataSource = new clsusersDataSource($this);
$this->ds = & $this->DataSource;
$this->InsertAllowed = true;
if($this->Visible)
{
$this->ComponentName = "users";
$this->Attributes = new clsAttributes($this->ComponentName . ":");
$CCSForm = explode(":", CCGetFromGet("ccsForm", ""), 2);
if(sizeof($CCSForm) == 1)
$CCSForm[1] = "";
list($FormName, $FormMethod) = $CCSForm;
$this->EditMode = ($FormMethod == "Edit");
$this->FormEnctype = "application/x-www-form-urlencoded";
$this->FormSubmitted = ($FormName == $this->ComponentName);
$Method = $this->FormSubmitted ? ccsPost : ccsGet;
$this->btn_register = new clsButton("btn_register", $Method, $this);
$this->username = new clsControl(ccsTextBox, "username", "Soldier", ccsText, "", CCGetRequestParam("username", $Method, NULL), $this);
$this->username->Required = true;
$this->user_email = new clsControl(ccsTextBox, "user_email", "User Email", ccsText, "", CCGetRequestParam("user_email", $Method, NULL), $this);
$this->user_email->Required = true;
$this->user_birthdate = new clsControl(ccsTextBox, "user_birthdate", "User Birthdate", ccsText, "", CCGetRequestParam("user_birthdate", $Method, NULL), $this);
$this->user_birthdate->Required = true;
}
}
//End Class_Initialize Event
//Initialize Method #2-052CBF13
function Initialize()
{
if(!$this->Visible)
return;
$this->DataSource->Parameters["urluid"] = CCGetFromGet("uid", NULL);
}
//End Initialize Method
//Validate Method #2-B7C6592D
function Validate()
{
global $CCSLocales;
$Validation = true;
$Where = "";
$Validation = ($this->username->Validate() && $Validation);
$Validation = ($this->user_email->Validate() && $Validation);
$Validation = ($this->user_birthdate->Validate() && $Validation);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "OnValidate", $this);
$Validation = $Validation && ($this->username->Errors->Count() == 0);
$Validation = $Validation && ($this->user_email->Errors->Count() == 0);
$Validation = $Validation && ($this->user_birthdate->Errors->Count() == 0);
return (($this->Errors->Count() == 0) && $Validation);
}
//End Validate Method
//CheckErrors Method #2-E8847328
function CheckErrors()
{
$errors = false;
$errors = ($errors || $this->username->Errors->Count());
$errors = ($errors || $this->user_email->Errors->Count());
$errors = ($errors || $this->user_birthdate->Errors->Count());
$errors = ($errors || $this->Errors->Count());
$errors = ($errors || $this->DataSource->Errors->Count());
return $errors;
}
//End CheckErrors Method
//Operation Method #2-6BA9892D
function Operation()
{
if(!$this->Visible)
return;
global $Redirect;
global $FileName;
$this->DataSource->Prepare();
if(!$this->FormSubmitted) {
$this->EditMode = $this->DataSource->AllParametersSet;
return;
}
if($this->FormSubmitted) {
$this->PressedButton = "btn_register";
if($this->btn_register->Pressed) {
$this->PressedButton = "btn_register";
}
}
$Redirect = $FileName . "?" . CCGetQueryString("QueryString", array("ccsForm"));
if($this->Validate()) {
if($this->PressedButton == "btn_register") {
if(!CCGetEvent($this->btn_register->CCSEvents, "OnClick", $this->btn_register) || !$this->InsertRow()) {
$Redirect = "";
}
}
} else {
$Redirect = "";
}
if ($Redirect)
$this->DataSource->close();
}
//End Operation Method
//InsertRow Method #2-C62BC29D
function InsertRow()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeInsert", $this);
if(!$this->InsertAllowed) return false;
$this->DataSource->username->SetValue($this->username->GetValue(true));
$this->DataSource->user_email->SetValue($this->user_email->GetValue(true));
$this->DataSource->user_birthdate->SetValue($this->user_birthdate->GetValue(true));
$this->DataSource->Insert();
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterInsert", $this);
return (!$this->CheckErrors());
}
//End InsertRow Method
//Show Method #2-AE9867B3
function Show()
{
global $CCSUseAmp;
$Tpl = CCGetTemplate($this);
global $FileName;
global $CCSLocales;
$Error = "";
if(!$this->Visible)
return;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeSelect", $this);
$RecordBlock = "Record " . $this->ComponentName;
$ParentPath = $Tpl->block_path;
$Tpl->block_path = $ParentPath . "/" . $RecordBlock;
$this->EditMode = $this->EditMode && $this->ReadAllowed;
if($this->EditMode) {
if($this->DataSource->Errors->Count()){
$this->Errors->AddErrors($this->DataSource->Errors);
$this->DataSource->Errors->clear();
}
$this->DataSource->Open();
if($this->DataSource->Errors->Count() == 0 && $this->DataSource->next_record()) {
$this->DataSource->SetValues();
if(!$this->FormSubmitted){
$this->username->SetValue($this->DataSource->username->GetValue());
$this->user_email->SetValue($this->DataSource->user_email->GetValue());
$this->user_birthdate->SetValue($this->DataSource->user_birthdate->GetValue());
}
} else {
$this->EditMode = false;
}
}
if($this->FormSubmitted || $this->CheckErrors()) {
$Error = "";
$Error = ComposeStrings($Error, $this->username->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_email->Errors->ToString());
$Error = ComposeStrings($Error, $this->user_birthdate->Errors->ToString());
$Error = ComposeStrings($Error, $this->Errors->ToString());
$Error = ComposeStrings($Error, $this->DataSource->Errors->ToString());
$Tpl->SetVar("Error", $Error);
$Tpl->Parse("Error", false);
}
$CCSForm = $this->EditMode ? $this->ComponentName . ":" . "Edit" : $this->ComponentName;
$this->HTMLFormAction = $FileName . "?" . CCAddParam(CCGetQueryString("QueryString", ""), "ccsForm", $CCSForm);
$Tpl->SetVar("Action", !$CCSUseAmp ? $this->HTMLFormAction : str_replace("&", "&", $this->HTMLFormAction));
$Tpl->SetVar("HTMLFormName", $this->ComponentName);
$Tpl->SetVar("HTMLFormEnctype", $this->FormEnctype);
$this->btn_register->Visible = !$this->EditMode && $this->InsertAllowed;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeShow", $this);
$this->Attributes->Show();
if(!$this->Visible) {
$Tpl->block_path = $ParentPath;
return;
}
$this->btn_register->Show();
$this->username->Show();
$this->user_email->Show();
$this->user_birthdate->Show();
$Tpl->parse();
$Tpl->block_path = $ParentPath;
$this->DataSource->close();
}
//End Show Method
} //End users Class #2-FCB6E20C
class clsusersDataSource extends clsDBlocalhost { //usersDataSource Class #2-5EDEDCFF
//DataSource Variables #2-8A9D7D42
public $Parent = "";
public $CCSEvents = "";
public $CCSEventResult;
public $ErrorBlock;
public $CmdExecution;
public $InsertParameters;
public $wp;
public $AllParametersSet;
public $InsertFields = array();
// Datasource fields
public $username;
public $user_email;
public $user_birthdate;
//End DataSource Variables
//DataSourceClass_Initialize Event #2-56B8B1F7
function clsusersDataSource(& $Parent)
{
$this->Parent = & $Parent;
$this->ErrorBlock = "Record users/Error";
$this->Initialize();
$this->username = new clsField("username", ccsText, "");
$this->user_email = new clsField("user_email", ccsText, "");
$this->user_birthdate = new clsField("user_birthdate", ccsText, "");
$this->InsertFields["soldier"] = array("Name" => "soldier", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_email"] = array("Name" => "user_email", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
$this->InsertFields["user_birthdate"] = array("Name" => "user_birthdate", "Value" => "", "DataType" => ccsText, "OmitIfEmpty" => 1);
}
//End DataSourceClass_Initialize Event
//Prepare Method #2-DC2F5FB8
function Prepare()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->wp = new clsSQLParameters($this->ErrorBlock);
$this->wp->AddParameter("1", "urluid", ccsInteger, "", "", $this->Parameters["urluid"], "", false);
$this->AllParametersSet = $this->wp->AllParamsSet();
$this->wp->Criterion[1] = $this->wp->Operation(opEqual, "uid", $this->wp->GetDBValue("1"), $this->ToSQL($this->wp->GetDBValue("1"), ccsInteger),false);
$this->Where =
$this->wp->Criterion[1];
}
//End Prepare Method
//Open Method #2-B071412E
function Open()
{
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildSelect", $this->Parent);
$this->SQL = "SELECT * \n\n" .
"FROM users {SQL_Where} {SQL_OrderBy}";
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteSelect", $this->Parent);
$this->query(CCBuildSQL($this->SQL, $this->Where, $this->Order));
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteSelect", $this->Parent);
}
//End Open Method
//SetValues Method #2-1C83BB75
function SetValues()
{
$this->username->SetDBValue($this->f("soldier"));
$this->user_email->SetDBValue($this->f("user_email"));
$this->user_birthdate->SetDBValue($this->f("user_birthdate"));
}
//End SetValues Method
//Insert Method #2-D2F97CD9
function Insert()
{
global $CCSLocales;
global $DefaultDateFormat;
$this->CmdExecution = true;
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeBuildInsert", $this->Parent);
$this->InsertFields["soldier"]["Value"] = $this->username->GetDBValue(true);
$this->InsertFields["user_email"]["Value"] = $this->user_email->GetDBValue(true);
$this->InsertFields["user_birthdate"]["Value"] = $this->user_birthdate->GetDBValue(true);
$this->SQL = CCBuildInsert("users", $this->InsertFields, $this);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "BeforeExecuteInsert", $this->Parent);
if($this->Errors->Count() == 0 && $this->CmdExecution) {
$this->query($this->SQL);
$this->CCSEventResult = CCGetEvent($this->CCSEvents, "AfterExecuteInsert", $this->Parent);
}
}
//End Insert Method
} //End usersDataSource Class #2-FCB6E20C
//Initialize Page #1-2A4101A9
// Variables
$FileName = "";
$Redirect = "";
$Tpl = "";
$TemplateFileName = "";
$BlockToParse = "";
$ComponentName = "";
$Attributes = "";
// Events;
$CCSEvents = "";
$CCSEventResult = "";
$TemplateSource = "";
$FileName = FileName;
$Redirect = "";
$TemplateFileName = "NewPage1.html";
$BlockToParse = "main";
$TemplateEncoding = "UTF-8";
$ContentType = "text/html";
$PathToRoot = "./";
$PathToRootOpt = "";
$Scripts = "|";
$Charset = $Charset ? $Charset : "utf-8";
//End Initialize Page
//Before Initialize #1-E870CEBC
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeInitialize", $MainPage);
//End Before Initialize
//Initialize Objects #1-1F103AC9
$DBlocalhost = new clsDBlocalhost();
$MainPage->Connections["localhost"] = & $DBlocalhost;
$Attributes = new clsAttributes("page:");
$Attributes->SetValue("pathToRoot", $PathToRoot);
$MainPage->Attributes = & $Attributes;
// Controls
$users = new clsRecordusers("", $MainPage);
$MainPage->users = & $users;
$users->Initialize();
$ScriptIncludes = "";
$SList = explode("|", $Scripts);
foreach ($SList as $Script) {
if ($Script != "") $ScriptIncludes = $ScriptIncludes . "<script src=\"" . $PathToRoot . $Script . "\" type=\"text/javascript\"></script>\n";
}
$Attributes->SetValue("scriptIncludes", $ScriptIncludes);
$CCSEventResult = CCGetEvent($CCSEvents, "AfterInitialize", $MainPage);
if ($Charset) {
header("Content-Type: " . $ContentType . "; charset=" . $Charset);
} else {
header("Content-Type: " . $ContentType);
}
//End Initialize Objects
//Initialize HTML Template #1-28F2FDD6
$CCSEventResult = CCGetEvent($CCSEvents, "OnInitializeView", $MainPage);
$Tpl = new clsTemplate($FileEncoding, $TemplateEncoding);
if (strlen($TemplateSource)) {
$Tpl->LoadTemplateFromStr($TemplateSource, $BlockToParse, "UTF-8");
} else {
$Tpl->LoadTemplate(PathToCurrentPage . $TemplateFileName, $BlockToParse, "UTF-8");
}
$Tpl->SetVar("CCS_PathToRoot", $PathToRoot);
$Tpl->block_path = "/$BlockToParse";
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeShow", $MainPage);
$Attributes->SetValue("pathToRoot", "");
$Attributes->Show();
//End Initialize HTML Template
//Execute Components #1-0C9864E9
$users->Operation();
//End Execute Components
//Go to destination page #1-810C207B
if($Redirect)
{
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
header("Location: " . $Redirect);
unset($users);
unset($Tpl);
exit;
}
//End Go to destination page
//Show Page #1-E3A8594F
$users->Show();
$Tpl->block_path = "";
$Tpl->Parse($BlockToParse, false);
if (!isset($main_block)) $main_block = $Tpl->GetVar($BlockToParse);
$main_block = CCConvertEncoding($main_block, $FileEncoding, $TemplateEncoding);
$CCSEventResult = CCGetEvent($CCSEvents, "BeforeOutput", $MainPage);
if ($CCSEventResult) echo $main_block;
//End Show Page
//Unload Page #1-4215F8E1
$CCSEventResult = CCGetEvent ($CCSEvents, "BeforeUnload", $MainPage);
$DBlocalhost->close();
unset($users);
unset($Tpl);
//End Unload Page
?>
You can submit the information via POST. The way you are submitting the data across is from a GET HTTP request. The best thing to do is submit it over via post data. I am assuming your frontend call is using ajax for the form submission? if not and using a simple form change method to POST. If it is using ajax, I would need to know if you are using something like jquery or crafting the XHR request yourself, but if you are doing it that way I would assume you would know the difference.
<form action="action_page.php" method="POST">
I am setting up a forgotten password and reset form. When I send my email. I have 2 issues. One is the unique code is not showing up in URL on when click on link. And the other issue I am having it says Message: Undefined variable: message.
Everything else works fine but just the code not showing up in URL and $message error.
Why is it not picking up my $code in URL. And having error $message?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Forgotten extends MX_Controller {
private $error = array();
public function __construct() {
parent::__construct();
if ($this->user->hasPermissionAccess() == TRUE) {
$this->lang->load('admin/english', 'english');
$this->lang->load('admin/common/forgotten', 'english');
$this->load->library('settings');
$this->load->library('pagination');
$this->load->library('request');
$this->load->library('response');
$this->load->library('document');
} else {
redirect('admin/error');
}
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->load->library('email');
$config['protocol'] = 'smpt';
$config['smpt_host'] = 'ssl://squid.arvixe.com';
$config['smpt_port'] = '465';
$config['smpt_user'] = '********'; // Username Blanked Out For Security
$config['smpt_password'] = '******'; // Password Blanked Out For Security
$this->email->initialize($config);
$this->email->from($config['smpt_user']);
$this->email->to($this->request->post['email']);
$subject = sprintf($this->lang->line('text_subject'), $this->settings->get('config_name'));
$this->email->subject($subject);
$code = sha1(uniqid(mt_rand(), true));
$this->load->model('admin/user/users_model');
$this->users_model->editCode($this->request->post['email'], $code);
$message .= sprintf($this->lang->line('text_greeting'), $this->settings->get('config_name')) . "\n\n";
$message .= $this->lang->line('text_change') . "\n\n";
$code = sha1(uniqid(mt_rand(), true));
$message .= site_url('admin/reset/', $code) . "\n\n";
$message .= sprintf($this->lang->line('text_ip'), $this->request->server['REMOTE_ADDR']) . "\n\n";
$this->email->message($message);
$this->email->send();
echo $this->email->print_debugger();
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => '<i class="fa fa-home"></i>' .' '. $this->lang->line('text_home'),
'href' => site_url('common/dashboard')
);
$data['breadcrumbs'][] = array(
'text' => $this->lang->line('heading_title'),
'href' => site_url('common/forgotten')
);
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = site_url('admin/forgotten');
$data['cancel'] = site_url('admin');
$data['heading_title'] = $this->lang->line('heading_title');
$data['text_your_email'] = $this->lang->line('text_your_email');
$data['text_email'] = $this->lang->line('text_email');
$data['entry_email'] = $this->lang->line('entry_email');
$data['button_reset'] = $this->lang->line('button_reset');
$data['button_cancel'] = $this->lang->line('button_cancel');
return $this->load->view('common/forgotten', $data);
}
public function validate() {
$this->load->model('admin/user/users_model');
if (!isset($this->request->post['email'])) {
$this->error['warning'] = $this->lang->line('error_email');
} elseif (!$this->users_model->getTotalUsersByEmail($this->request->post['email'])) {
$this->error['warning'] = $this->lang->line('error_email');
}
return !$this->error;
}
}
Found issue where the first $message . was it should just be $message no full stop. And for code problem I changed the site_url to base.
$message = sprintf($this->lang->line('text_greeting'), $this->settings->get('config_name')) . "\n\n";
$message .= $this->lang->line('text_change') . "\n\n";
$code = sha1(uniqid(mt_rand(), true));
$message .= base_url('admin/reset') . '/' . $code . "\n\n";
$message .= sprintf($this->lang->line('text_ip'), $this->request->server['REMOTE_ADDR']) . "\n\n";
$this->email->message($message);
Re-visiting this problem specified in my previous question, I tried and tried, also with different accounts (I tried gmail, as well as outlook), but the problem still persists. The error I get is the following if I try to access my google account
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {imap.gmail.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
if I try accessing email on my outlook account, the error is the same :
Error: Unable to get imap_thread after 4 retries. 'Can't open mailbox {outlook.office365.com:993/ssl/imap/tls/novalidate-cert}INBOX: invalid remote specification'
My setup is as follows :
public $emailTicket = array(
'datasource' => 'ImapSource',
'server' => 'outlook.office365.com',
'connect' => 'imap/tls/novalidate-cert',
'username' => 'my email here',
'password' => 'my password here',
'port' => '993', //incoming port
'ssl' => true,
'encoding' => 'UTF-8',
'error_handler' => 'php',
'auto_mark_as' => array(
'Seen',
// 'Answered',
// 'Flagged',
// 'Deleted',
// 'Draft',
),
);
I am working on a local machine, does anyone know if this might be the problem or not? Has anyone ever tried this and worked for him/her? I am open to all input!
I can't seem to find what's wrong here, I've been at this for about 2days now, so if anyone can help, I appreciate it!
Also here's the link for the plugin i'm using, by Nicolas Ramy..
You can use the following implemented code to fulfill your requirements:
public function generate_email_response_pdf()
{
$this->layout = false;
$this->autoRender = false;
$username = EMP_SMTP_MAIL_FROM;
$password = EMP_SMTP_MAIL_PASSWORD;
$imap = imap_open('{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX', $username, $password);
$emails = imap_search($imap, 'ALL');
if(!empty($emails))
{
//put the newest emails on top
rsort($emails);
foreach($emails as $email_number)
{
$flag = 0;
$mail_data = array();
$file_name = array();
$output = array();
$savefilename = null;
$filename = null;
$overview = imap_fetch_overview($imap, $email_number, 0);
//initialize the subject index with -000, considering not receving this will not be received in
//subject line of email
$output['subject'] = '-000x';
if(isset($overview[0] -> subject))
{
$output['subject'] = $overview[0] -> subject;
}
$structure = imap_fetchstructure($imap, $email_number);
if(property_exists($structure, 'parts'))
{
$flag = 1;
$flattened_parts = $this->flatten_parts($structure->parts);
foreach($flattened_parts as $part_number => $part)
{
switch($part->type)
{
case 0:
//the HTML or plain text part of the email
if((isset($part->subtype)=='HTML')&&(isset($part->disposition)=='ATTACHMENT'))
{
$part_number = 1.2;
}
else if(isset($part->subtype)=='HTML')
{
$part_number = $part_number;
}
else
{
$part_number = $part_number;
}
$message = $this->get_part($imap, $email_number, $part_number, $part->encoding);
//now do something with the message, e.g. render it
break;
case 1:
// multi-part headers, can ignore
break;
case 2:
// attached message headers, can ignore
break;
case 3: // application
case 4: // audio
case 5: // image
case 6: // video
case 7: // other
break;
}
if(isset($part->disposition))
{
$filename = $this->get_filename_from_part($part);
if($filename)
{
// it's an attachment
$attachment = $this->get_part($imap, $email_number, $part_number, $part->encoding);
$file_info = pathinfo($filename);
$savefilename = RESPONSE_ATTACHMENT_PREFIX.$file_info['filename'].'_'.$this->_getRandId(4).'.'.$file_info['extension'];
$file_name[] = $savefilename;
$attachment_file_name = $this->save_attachment($attachment, $savefilename, $directory_path);
//imap_fetchbody($imap, $email_number, 2); //This marks message as read
}
else
{
// don't know what it is
}
}
}
}
else
{
$encoding = $structure->encoding;
$message = imap_fetchbody($imap, $email_number, 1.2);
//echo $message; die;
if($message == "")
{
$message = imap_body($imap, $email_number);
if($encoding == 3)
{
$message = base64_decode($message);
}
else if($encoding == 4)
{
$message = quoted_printable_decode($message);
}
}
}
$header = imap_headerinfo($imap, $email_number);
$from_email = $header->from[0]->mailbox."#".$header->from[0]->host;
$to_email = $header->to[0]->mailbox."#".$header->to[0]->host;
$reply_to_email = $header->reply_to[0]->mailbox."#".$header->reply_to[0]->host;
$cc_email = array();
if(isset($header->cc))
{
foreach($header->cc as $ccmail)
{
$cc_email[] = $ccmail->mailbox.'#'.$ccmail->host;
}
$cc_email = implode(", ", $cc_email);
}
$output['to'] = $to_email;
$output['from'] = $from_email;
$output['reply_to'] = $reply_to_email;
$output['cc'] = $cc_email;
$formatted_date = date('D, d M Y h:i A', strtotime($overview[0] -> date));
$output['date'] = $formatted_date;
$output['message'] = $message;
$output['flag'] = $flag;
$mail_data['Attachment'] = $file_name;
$mail_data['Data'] = $output;
$this->set('response_data', $mail_data);
$mail_content = null;
if(!empty($mail_data))
{
$this->viewPath = 'Elements/default';
$mail_content = $this->render('pdf_content');
}
$header = null;
$footer = null;
$html = preg_replace(array('/[^\r\n\t\x20-\x7E\xA0-\xFF]*/'), '', $mail_content);
$pdfFile = $this->_generateWkPdf($html, $directory_path, $new_file_name, $header, $footer);
$image_type = EXT_JPG;
$response_files_array = $this->_generateImagesFromPdf($directory_path.$pdfFile, $directory_path, $new_file_name, $image_type);
}
}
imap_close($imap);
}
I have written/copied a script that reads emails from an inbox and updates a ticket and then moves the email to a proccessed folder. This all works perfectly on new emails to the inbox but when someone replys to an email and it ends up in the inbox my scrtipt reads nothing on the email.
Is there something different to the way an email is structured when its a reply? I need a way of reading whats in the email so I can update a ticket with the contents. Knowing which email it is to update is all taken care of its just purely reading the content Im struggling with.
Here is the code
class Email
{
// imap server connection
public $conn;
// inbox storage and inbox message count
public $inbox;
private $msg_cnt;
// email login credentials
private $server = '????????????';
private $user = '????????';
private $pass = '?????????????';
private $port = ??;
// connect to the server and get the inbox emails
function __construct()
{
$this->connect();
$this->inbox();
}
function getdecodevalue($message,$coding)
{
switch($coding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message=imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
// close the server connection
function close()
{
$this->inbox = array();
$this->msg_cnt = 0;
imap_close($this->conn);
}
// open the server connection
// the imap_open function parameters will need to be changed for the particular server
// these are laid out to connect to a Dreamhost IMAP server
function connect()
{
$this->conn = imap_open("{".$this->server.":".$this->port."/imap/novalidate-cert}INBOX", $this->user, $this->pass);
}
// move the message to a new folder
function move($msg_index, $folder='Read')
{
// move on server
imap_mail_move($this->conn, $msg_index, $folder);
// re-read the inbox
//$this->inbox();
}
// get a specific message (1 = first email, 2 = second email, etc.)
function get($msg_index=NULL)
{
if(count($this->inbox) <= 0)
{
return array();
}
elseif( ! is_null($msg_index) && isset($this->inbox[$msg_index]))
{
return $this->inbox[$msg_index];
}
return $this->inbox[0];
}
// read the inbox
function inbox()
{
$this->msg_cnt = imap_num_msg($this->conn);
$in = array();
for($i = 1; $i <= $this->msg_cnt; $i++)
{
$in[] = array(
'index' => $i,
'header' => imap_headerinfo($this->conn, $i),
'body' => $this->cleanBody(imap_fetchbody($this->conn, $i,1)),
'structure' => imap_fetchstructure($this->conn, $i)
);
}
$this->inbox = $in;
}
function cleanBody($body)
{
$delimiter = '#';
$startTag = '----------START REPLY----------';
$endTag = '----------END REPLY----------';
$regex = $delimiter . preg_quote($startTag, $delimiter)
. '(.*?)'
. preg_quote($endTag, $delimiter)
. $delimiter
. 's';
preg_match($regex,$body,$matches);
$ret = trim($matches[1]);
return $ret;
}
}
$emails = new Email();
$email = array();
$emailCount = 1;
foreach($emails->inbox as $ems => $em)
{
$email[$emailCount]['subject'] = $sub = $em['header']->subject;
//echo $sub;
$subParts = explode('-',$sub);
$ticketUniqueCode = trim($subParts[1]);
$sql = "SELECT * FROM ticket_main WHERE uniquecode = '".mysql_escape_string($ticketUniqueCode)."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query))
{
$res = mysql_fetch_object($query);
$ticketBody = $em['body'];
$customerID = $res->customerID;
$sql2 = "INSERT INTO ticket_updates SET ticketID = '".$res->ticketID."' , submitted = NOW() , submittedBy = '".$res->customerID."' , message = '".mysql_escape_string($ticketBody)."' , inhouse = 0";
$query = mysql_query($sql2);
// attachment section
$message_number = $em['index'];
$attachments = array();
if(isset($em['structure']->parts) && count($em['structure']->parts))
{
//echo 'hi';
for($i = 0; $i < count($em['structure']->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($em['structure']->parts[$i]->ifdparameters) {
foreach($em['structure']->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($em['structure']->parts[$i]->ifparameters) {
foreach($em['structure']->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($emails->conn, $message_number, $i+1);
if($em['structure']->parts[$i]->encoding == 3)
{ // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($em['structure']->parts[$i]->encoding == 4)
{ // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
if(isset($em['structure']->parts[$i]->disposition) && $em['structure']->parts[$i]->disposition == "attachment")
{
$filename = $attachments[$i]['name'];
$mege="";
$data="";
$mege = imap_fetchbody($emails->conn, $message_number, $i+1);
$filename= $filename;
$fp=fopen('???????????????'.$filename,"w");
$data=$emails->getdecodevalue($mege,$em['structure']->parts[$i]->type);
fputs($fp,$data);
fclose($fp);
$email[$emailCount]['attachment'] = $attachments;
}
}
}
}
$emailCount++;
}
$emailNumbers = imap_search($emails->conn,'ALL');
if(!empty($emailNumbers))
{
foreach($emailNumbers as $a)
{
$emails->move($a);
}
imap_expunge($emails->conn);
}
$emails->close();
Hope that makes some sense and someone can actually help.
Many many thanks in advance
Jon
Well the most obvious thing is your code assumes a message is always in part 1, your line:
'body' => $this->cleanBody(imap_fetchbody($this->conn, $i,1)),
Means it's only looking at body 1. If it's a pure text email body 1 will be right, but if it's multipart/alternative (text & html) body 1 would be the base MIME message which tells you that there are sub bodies (body 1.1, 1.2) that actually contain the content.
Further if the reply includes embedded images, or includes the message it's replying to as an attachment then you could have even more bodies/locations.
So how do I find the body? (you ask)... well you can use imap_fetchstructure to learn about all the body parts, then search through it to find a piece with type=0 (text) and then download that body part. (The first found text should be the right one, but note there could be more than one text body type in an email).