form doesn't get sent with PHPMailer() - php

can someone help me a bit with PhpMailer form? I'm not a php dev and i'm a bit lost, mostly because I have no idea how to debug it.
Tips how to debug such scripts are very welcome! (I don't know how to do it in localhost and I host it in a web shared host so I cannot ssh the server)
This is the script:
I have a multiple step form from Frontend which has also recaptcha, so the script include validation of different form steps and recaptcha validation.
<?php
require_once("/PHPMailer/PHPMailer.php");
use PHPMailer\PHPMailer\PHPMailer;
$t_mailer = new PHPMailer;
$t_mailer->SMTPAuth = true;
$t_mailer->Username = "myemail#gmail.com"; // gmail username
$t_mailer->Password = "****"; //gmail password
$t_mailer->SMTPSecure = 'tls';
$t_mailer->Port = 587;
$t_mailer->setFrom("myemail#gmail.com", "Name for the owner of the Account");
//$t_mailer->addAddress("myemail#gmail.com", "Name for who is being sent the email.");
$t_mailer->Subject = "Project request from ECA";
$t_mailer->Body = "This will be the message body that is sent.";
// $recipient = 'myemail#gmail.com'; // Enter the recipient's email address here.
// $subject = 'Project request from ECA'; // Enter the subject of the email here.
$success = 'Your message was sent successful. Thanks.';
$error = 'Sorry. We were unable to send your message.';
$invalid = 'Validation errors occurred. Please confirm the fields and submit it again.';
if ( ! empty( $_POST ) ) {
require_once('recaptcha.php');
if( isset( $_POST['email'] ) ) {
$from = filter_var( $_POST['email'], FILTER_VALIDATE_EMAIL );
} else {
$from = null;
}
if( isset( $_POST['step'] ) ) {
$step = $_POST['step'];
} else {
$step = 'send';
}
if ( ! empty( $_POST['reCAPTCHA'] ) ) {
if ( ! empty( $reCAPTCHA['success'] ) ) {
$errCaptcha = '';
} else {
$errCaptcha = true;
}
} else {
$errCaptcha = '';
}
$errFields = array();
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
if ( $key == 'email' ) {
$validation = filter_var( $_POST[$key], FILTER_VALIDATE_EMAIL );
} else {
$validation = ! empty( $_POST[$key] );
}
if ( ! $validation ) {
$errFields[$key] = true;
}
}
}
if ( empty( $errCaptcha ) && count( $errFields ) === 0 && $step === 'send' ) {
$header = "From: " . $from . " <" . $from . ">" . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$body = '<table style="padding: 35px; background-color: #f5f5f5"; font-family: Roboto, sans-serif; font-size: 1rem; text-align: left; border-radius: 4px>';
$body .= '<tr><th style="font-size: 1.5rem; font-weight: 600; color: #1E50BC">'.$subject.'</th></tr>';
$body .= '<tr></td>';
foreach( $_POST as $key => $value ) {
if ( $key != 'section' && $key != 'reCAPTCHA' ) {
$body .= '<p><b>' . str_replace( '-', ' ', ucfirst( $key ) ) . '</b>: ' . $value . '</p>';
}
}
$body .= '</td></tr>';
$body .= '</table>';
$t_mailer->Body = $body;
$t_mailer->addAddress($from, 'who send the email');
// $mail = mail( $recipient, $subject, $body, $header );
// $mail
if ( $t_mailer->send() ) {
$response = array(
'status' => 'success',
'info' => $success
);
print_r( json_encode( $response ) );
} else {
$response = array(
'status' => 'fail',
'info' => $error
);
print_r( json_encode( $response ) );
}
} else {
$response = array(
'status' => 'invalid',
'info' => $invalid,
'captcha' => $errCaptcha,
'fields' => $errFields,
'errors' => count( $errFields )
);
print_r( json_encode( $response ) );
}
exit;
}
I'm sure PhpMailer works with my host and my server because I tried a very simple script that send an email from root and it worked. (I got the email in my gmail inbox)
But This script is in another folder, not root, even tho they all have same folder/files permission (not sure if is relevant, but better specify!)

Several things not quite right here.
When you're using PHPMailer without composer, you need to load all the classes it needs yourself, so add:
require_once '/PHPMailer/SMTP.php';
require_once '/PHPMailer/Exception.php';
You are setting some SMTP config properties, but not actually telling PHPMailer to use SMTP, so add this:
$t_mailer->isSMTP();
You're sending from a gmail address, which means you must send through gmail's servers (or you will fail SPF checks), but you have not specified a server to send through, so set this:
$t_mailer->Host = 'smtp.gmail.com';
Your content is in HTML, but you're not asking PHPMailer to send it as HTML:
$t_mailer->isHTML();
You don't need any of that stuff you're doing with $header; PHPMailer does all that for you.
Rather than going any further, I'd recommend basing your code on the gmail example provided with PHPMailer, and if you run into any other issues, refer to the PHPMailer troubleshooting guide and search on here.

Related

Getting Gmail emails in read status with Imap PHP

I take data from Gmail with this code
<?php $data = array(
// email account
'email' => array(
'hostname' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => $emailAddress,
'password' => $emailPassword
),
// inbox pagination
'pagination' => array(
'sort' => $sortBy,
'limit' => 10,
'offset' => $offset
)
);
$result = array();
$imap = imap_open($data['email']['hostname'], $data['email']['username'], $data['email']['password']) or die ('Cannot connect to yourdomain.com: ' . imap_last_error());
$read = imap_search($imap, 'ALL');
$overview = imap_fetch_overview($imap, $read[$i], 0);
$header = imap_headerinfo($imap, $read[$i], 0);
$mail = $header->from[0]->mailbox . '#' . $header->from[0]->host;
$image = '';
$structure = imap_fetchstructure($imap, $read[$i]);
if(isset($structure->parts) && is_array($structure->parts) && isset($structure->parts[1])) {
$part = $structure->parts[1];
if($part->encoding == 3) {
$message = imap_fetchbody($imap,$read[$i],1.2);
$message = imap_qprint($message);
} else if($part->encoding == 1) {
$message = imap_8bit($message);
} else {
$message = imap_fetchbody($imap,$read[$i],2);
$message = imap_qprint($message);
}
}else{
$message = imap_body($imap, $read[$i],0);
}
?>
All data I receive correctly, however when I enter Email list page, the received emails turn to read.
It worked fine before, after using for some time, this issue appeared.
Any idea what can be the reason?
In imap_fetchbody, add the FT_PEEK flag to prevent clearing the \Seen flag automatically.
imap_fetchbody($imap, $read[$i], 1.2, FT_PEEK);
See option flag documentation at the official site.

Sending by email existing multiple files attachments. smarty/php

I need to send multiple files attachments existing in database, with this code WORKS TO SEND ONLY ONE FILE (choosing any from loop). But I will need to send more than on file. Please help me in this matter, I really appreciate. Please ask me anything. Thank you.
////////// THE FORM PAGE
<form novalidate="novalidate" action="{$CMS_base_url}admin/employee_view_email.php?id={$id}" method="post" enctype="multipart/form-data">
<input type="hidden" id="id" name="id" value="{$id}" />
{if is_array ($cvs) && $cvs != "" }
<table class="table table-hover">
<thead>
<tr>
<th class="col-md-2">Create date</th>
<th class="col-md-7">Document name / Description</th>
<th class="col-md-3">Select All <input type="checkbox" name="all" id="all" value="1" onclick="checkUncheckAll(this);" /></th>
<th class="col-md-3">Download</th>
</tr>
</thead>
<tbody>
{foreach from=$cvs key=k item=i}
<tr>
<td><em>{$i.createdAt}</em></td>
<td><strong>{$i.title}</a></strong></td>
<td><input type="checkbox" name="txt_existed_cv_attach" id="txt_existed_cv_attach" value="{$i.id}" /></td>
<td>Download</td>
</tr>
{/foreach}
{else}
<tr>
<td>{lang mkey='error' skey='noResult'}</td>
<td>Upload a new document to send by Admin Email {lang mkey='info' skey='fileAttachments'}</td>
<td colspan="2"><input class="btn-u btn-u-dark-blue" type="file" name="txt_cv_attach" id="txt_cv_attach" multiple="multiple"></td>
</tr>
</tbody>
{/if}
</table>
<input type="submit" name="bt_send_atach" value="SEND EMAIL TO ADMIN" class="btn-u btn-u-lg btn-u-dark-blue pull-left" />
</form>
////////// PAGE FOR fetching ('admin/employeeView.tpl') the FORM PAGE
$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );
require (CMS_LIB_PATH.DS.'class.cv.php');
///... more classes for employee/user to fetching the related page
$cvs = CV::manageEmployeeCV( $id );
if ( is_array($cvs) and !empty($cvs) )
{
$temp = array();
$i=1;
foreach( $cvs as $cv )
{
$showTo = lang('select','cvShowType');
$temp[$i]['id'] = $cv->id;
$temp[$i]['name'] = $cv->originalName;
$temp[$i]['type'] = $cv->fileType;
$temp[$i]['tmp_name'] = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv->fileName;
$temp[$i]['error'] = 0;
$temp[$i]['size'] = $cv->fileSize;
$temp[$i]['title'] = $cv->title;
$temp[$i]['description'] = $cv->description;
$temp[$i]['showTo'] = $showTo[$cv->showTo];
$temp[$i]['defaultCV'] = $cv->defaultCV;
$temp[$i]['createdAt'] = strftime(dateFormat, strtotime($cv->createdAt) );
$temp[$i]['modifyAt'] = strftime(dateFormat, strtotime($cv->modifyAt) );
$temp[$i]['noViews'] = $cv->noViews;
$temp[$i]['employee_id'] = $cv->employeeIDFK;
$i++;
}
$smarty->assign( 'cvs', $temp );
}
$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$smarty->assign( 'message', $session->getMessage() );
$smarty->assign('rendered_page', $smarty->fetch('admin/employeeView.tpl') );
$smarty->display('admin/index.tpl');
$session->unsetMessage();
////////// CLASS.CV.PHP PAGE WITH DATABASE QUERY FOR LINE
public static function getCVByEmployee( $id=0, $employee_id=0 )
{
global $database, $db;
$sql = " SELECT * FROM ". self::$table_name;
$sql .= " WHERE id=".$db->escape_value($id)." AND employeeIDFK=".(int)$employee_id;
$sql .= " LIMIT 1 ";
$result = self::find_by_sql( $sql );
return !empty($result) ? array_shift($result) : false;
}
// .$db->escape_value($id). // Other page with more DATABASE CLASSES
public function escape_value ( $string ){
if( $this->mysqli_real_escape_string ){
if($this->magic_quotes_active){ $string=stripslashes($string); }
$string = mysqli_real_escape_string($this->connection, $string);
}else{
if(!$this->magic_quotes_active){ $string= addslashes($string); }
}
return $string;
}
////////// EMAIL PROCESS PAGE .....admin/employee_view_email.php?id={$id}
$id = (int)$_GET['id'];
$smarty->assign('id', $id );
$employee = Employee::find_by_id( $id );
///... more classes for employee/user data to send my email
include_once CMS_LIB_PATH.DS.'class.cv.php';
$cvFile = $_FILES['txt_cv_attach'];
$cv_already_existed = $_POST['txt_existed_cv_attach'];
if($cv_already_existed != '' )
{
include_once CMS_LIB_PATH.DS.'class.cv.php';
$cvFile = array();
$user_id = $session->getUserID();
$cv_f = CV::getCVByEmployee( $cv_already_existed, $id );
$cvFile['name'] = $cv_f->originalName;
$cvFile['type'] = $cv_f->fileType;
$cvFile['tmp_name'] = CMS_SITE_ROOT.DS.'curriculum_vitae_file'.DS.$cv_f->fileName;
$cvFile['error'] = 0;
$cvFile['size'] = $cv_f->fileSize;
}
else
{
/*
* check for upload file
*/
if( $cvFile['error'] == 4 )
{
$errors[] = lang( 'error', 'noCVFileApplication');
}
if( $cvFile['error'] == 0 )
{
$ext = end(explode(".", basename($cvFile['name']) ));
$ext = strtolower($ext);
if( !in_array($ext, $allowed_files) )
{
$e = lang('error', 'fileNotAllowed');
$e = str_replace('#file_name#', basename($cvFile['name']) , $e );
$errors[] = $e;
}
if($cvFile['size'] > max_upload_cv_size )
{
$errors[] = lang('error', 'max_file_size');
}
}
}
if( $employee)
{
$full_name = $employee->full_name();
$from = array("email" => no_reply_email, "name" => $full_name );
include CMS_LANGUAGE.DS.'emailTemplate.php';
//send email to admin
$to = array("email" => notify_email, "name" => site_name );
$emailTemplate = lang('email_template','notify_candidate_view_email');
$subject = $emailTemplate['subject'];
$body = $emailTemplate['body'];
$body = str_replace( "#full_name#", $full_name , $body );
$body = str_replace( "#firstName#", $employee->firstName , $body );
$body = str_replace( "#middleName#", $employee->middleName, $body );
$body = str_replace( "#surname#", $employee->surname, $body );
$body = str_replace( "#address#", $employee->address, $body );
$body = str_replace( "#cv_title#", $cv_f->originalName, $body );
$body = str_replace( "#cv_type#", $cv_f->fileType, $body );
$body = str_replace( "#user_id#", $user_id , $body );
$emailBody= array('html' => $body, 'plain' => $body );
$mail = sendMail( $from, $to, $subject, $emailBody, $cvFile);
unset( $_SESSION['account'] );
$message = '<div class="alert success">'.lang('success','email_send_to_admin').'</div>';
}
else
{
$message = lang( 'error', 'errorHead' );
$message .= "<ul> <li />";
$message .= join(" <li /> ", $employee->errors );
$message .= "</ul>";
$message = "<div class='alert error'>".$message."</div>";
}
$smarty->assign( 'cvs', $temp );
$smarty->assign('employee', $employee );
$smarty->assign('lang', $lang);
$session->setMessage( $message );
redirect_to( CMS_BASE_URL . 'admin/employee_view.php?id='.$id );
exit;
////////// SEND EMAIL CLASS PAGE
function sendMail( $from='', $to='', $subject='', $message='', $cvFile='', $clFile='' )
{
global $smarty;
if( $cvFile || !empty($cvFile) || is_array($cvFile) )
{
$CV_temp_path = $cvFile['tmp_name'];
$CV_filename = basename($cvFile['name']);
$CV_type = $cvFile['type'];
$CV_size = $cvFile['size'];
}
if( mail_type == 1 )
{
$mail->IsSMTP();
$mail->Host = "ukm3.siteground.biz";
$mail->Port = "465";
$mail->SMTPSecure = "ssl";
$mail->SMTPAuth = true;
$mail->Username = "admin username";
$mail->Password = "password";
}
try {
$mail->AddAddress($to_email, $to_name);
$mail->SetFrom($from_email, $from_name); //email, name
$mail->Sender=$from_email;
$mail->Subject = $subject;
$mail->AltBody = $plain;
$mail->MsgHTML($html);
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
{
$mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
}
return $mail->Send();
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //error messages from PHPMailer
die;
}
catch (Exception $e)
{
echo $e->getMessage(); //error messages from anything else!
die;
}
}
It is hard to judge all your code (also because things are included that I don't know), but it looks like here is the problem:
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) )
{
$mail->AddAttachment($CV_temp_path, $CV_filename, "base64", $CV_type); // attachment
}
You want multiple attachment added, not 1.
You give the array $cvFile (poorly named. Name it something like $cvFileArr to make it clear. Now it looks like a single name/path).
SO I expect you need some looping over the values, like this (not tested):
if( !empty($cvFile) && is_array($cvFile) && !empty($CV_filename) ) {
foreach($cvFile as $oneFile){
$mail->AddAttachment($CV_temp_path, $oneFile, "base64", $CV_type); // attachment
}
}
But it is hard to tell exactly. But I expect you need to $mail->AddAttachment for each file you have.

PHP email validation script

My first post here, although i have used this site many times to find fixes for code.
I've been using a script to validate emails on my old host which works fine, the new host however (123-reg) it doesnt validate them correctly at all.
This script actually verifies the existence of an email not just the format of it.
please see the following links
t43.co.uk/emailcheck.php?email=asdasdasd#hotmail.com (works fine)
smile-database.co.uk/emailcheck.php?email=asdasdasd#hotmail.com (always says valid when i know it isnt)
my script is below.
function checkEmail( $email, $chFail = false )
{
$msgs = Array();
$msgs[] = 'Received email address: '.$email;
if( !preg_match( "/^(([^<>()[\]\\\\.,;:\s#\"]+(\.[^<>()[\]\\\\.,;:\s#\"]+)*)|(\"([^\"\\\\\r]|(\\\\[\w\W]))*\"))#((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([a-z\-0-9áàäçéèêñóòôöüæøå]+\.)+[a-z]{2,}))$/i", $email ) )
{
$msgs[] = 'Email address was not recognised as a valid email pattern<br><br>';
return $chFail ? Array( false, $msgs ) : false;
}
$msgs[] = 'Email address was recognised as a valid email pattern';
//get the mx host name
if( preg_match( "/#\[[\d.]*\]$/", $email ) )
{
$mxHost[0] = preg_replace( "/[\w\W]*#\[([\d.]+)\]$/", "$1", $email );
$msgs[] = 'Email address contained IP address '.$mxHost[0].' - no need for MX lookup';
}
else
{
//get all mx servers - if no MX records, assume domain is MX (SMTP RFC)
$domain = preg_replace( "/^[\w\W]*#([^#]*)$/i", "$1", $email );
if( !getmxrr( $domain, $mxHost, $weightings ) )
{
$mxHost[0] = $domain;
$msgs[] = 'Failed to obtain MX records, defaulting to '.$domain.' as specified by SMTP protocol';
}
else
{
array_multisort( $weightings, $mxHost );
$cnt = ''; $co = 0; foreach( $mxHost as $ch ) { $cnt .= ( $cnt ? ', ' : '' ) . $ch . ' (' . $weightings[$co] . ')'; $co++; }
$msgs[] = 'Obtained the following MX records for '.$domain.': '.$cnt;
}
}
//check each server until you are given permission to connect, then check only that one server
foreach( $mxHost as $currentHost )
{
$msgs[] = 'Checking MX server: '.$currentHost;
if( $connection = #fsockopen( $currentHost, 25 ) )
{
$msgs[] = 'Created socket ('.$connection.') to '.$currentHost;
if( preg_match( "/^2\d\d/", $cn = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent SMTP connection header - no futher MX servers will be checked: '.$cn;
while( preg_match( "/^2\d\d-/", $cn ) )
{
$cn = fgets( $connection, 1024 );
$msgs[] = $currentHost.' sent extra connection header: '.$cn;
}
if( !$_SERVER )
{
global $HTTP_SERVER_VARS; $_SERVER = $HTTP_SERVER_VARS;
}
//attempt to send an email from the user to themselves (not <> as some misconfigured servers reject it)
echo $_SERVER['HTTP_HOST'] . "<BR>";
$localHostIP = gethostbyname(preg_replace("/^.*#|:.*$/",'',$_SERVER['HTTP_HOST']));
echo $localHostIP . "<BR>";
$localHostName = gethostbyaddr($localHostIP);
fputs( $connection, 'HELO '.($localHostName?$localHostName:('['.$localHostIP.']'))."\r\n" );
if( $success = preg_match( "/^2\d\d/", $hl = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent HELO response: '.$hl;
fputs( $connection, "MAIL FROM: <$email>\r\n" );
if( $success = preg_match( "/^2\d\d/", $from = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent MAIL FROM response: '.$from;
fputs( $connection, "RCPT TO: <$email>\r\n" );
if( $success = preg_match( "/^2\d\d/", $to = fgets( $connection, 1024 ) ) )
{
$msgs[] = $currentHost.' sent RCPT TO response: '.$to;
}
else
{
$msgs[] = $currentHost.' rejected recipient: '.$to;
}
}
else
{
$msgs[] = $currentHost.' rejected MAIL FROM: '.$from;
}
}
else
{
$msgs[] = $currentHost.' rejected HELO: '.$hl;
}
fputs( $connection, "QUIT\r\n");
fgets( $connection, 1024 ); fclose( $connection );
//see if the transaction was permitted (i.e. does that email address exist)
$msgs[] = $success ? ('Email address was accepted by '.$currentHost) : ('Email address was rejected by '.$currentHost);
return $chFail ? Array( $success, $msgs ) : $success;
}
elseif ( preg_match( "/^550/", $cn ) )
{
$msgs[] = 'Mail domain denies connections from this host - no futher MX servers will be checked: '.$cn;
return $chFail ? Array( false, $msgs ) : false;
}
else
{
$msgs[] = $currentHost.' did not send SMTP connection header: '.$cn;
}
}
else
{
$msgs[] = 'Failed to create socket to '.$currentHost;
}
}
$msgs[] = 'Could not establish SMTP session with any MX servers';
return $chFail ? Array( false, $msgs ) : false;
}
echo "<br><br>Email Validation Check<br><br>";
$return_msgs = checkEmail( $_REQUEST['email'], true );
if ( $return_msgs[0] == 0 )
{
echo "<img src='img/Fail.png'> May be invalid<br>".$_REQUEST['email'];
}
elseif ( $return_msgs[0] == 1 )
{
echo "<img src='img/OK.png'> Valid<br>".$_REQUEST['email'];
}
else
{
echo "<img src='img/Caution.png'> Caution<br>".$_REQUEST['email'];
}
I have read one great topic about email validation.
Author propose to use this regexp: /.+#.+\..+/i and give a great description (in Russian) to a lot of "why exactly this regexp"
'somestring' # 'somestring'.'somestring'

Send email using gmail smtp in zend? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
email zend framwork smtp
I have following configuration:
smtp.type = Zend_Mail_Transport_Smtp
smtp.smtpServer = "smtp.gmail.com"
smtp.username = "ddd#gmail.com"
smtp.password = "dddd"
smtp.email = "ddd#gmail.com"
smtp.port = "587"
smtp.ssl = "tls"
smtp.auth = "login"
I am getting following error:
5.7.0 Must issue a STARTTLS command first. 74sm813723wem.41
My COde:
public function sendEmail( $mailData, $bootstrap = null ) {
// Get SMTP server configurations
if ( $bootstrap == null ) {
$front = Zend_Controller_Front::getInstance();
$bootstrap = $front->getParam('bootstrap');
}
$smtpSettings = $bootstrap->getOption('smtp');
print_r($smtpSettings);
// Only pass username password settings if the authentication is required.
if ( $smtpSettings['auth'] == 'login' ) {
$config = array('ssl' => $smtpSettings['ssl'],
'username' => $smtpSettings['username'],
'password' => $smtpSettings['password']);
$transport = new Zend_Mail_Transport_Smtp( $smtpSettings['smtpServer'], $config );
} else {
$transport = new Zend_Mail_Transport_Smtp( $smtpSettings['smtpServer'] );
}
$mail = new Zend_Mail( 'utf-8' );
try {
if ( $mailData['user'] == true ) {
$mail->setFrom( $mailData['from'], $mailData['fromName'] );
} else {
$mail->setFrom( $smtpSettings['email'], "eCHDP" );
}
// Do we have a single reciepent or multiple receipents?
if ( !is_array($mailData['to']) ) {
$mail->addTo( $mailData['to'] , $mailData['toName'] );
} else {
// We have multiple receipents. Add all of them.
foreach ( $mailData['to'] as $id => $value ) {
$mail->addTo( $value , $mailData['toName'][$id] );
}
}
$mail->setSubject( $mailData['subject'] );
$mail->setBodyHtml( $mailData['body'] );
// If attachment found then attach
if ( $mailData['attachment'] ) {
$attach = new Zend_Mime_Part( file_get_contents( $mailData['attachment'] ) );
$attach->type = 'application/pdf';
$attach->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$attach->filename = 'Invoice.pdf';
$mail->addAttachment( $attach );
}
$mail->send( $transport );
return true;
} catch ( Exception $e ) {
echo "Error sending Email : ";
$logger = Zend_Registry::get('Logger');
$logger->err($e->getMessage());
echo $e->getMessage() . "\n\n\n";
return false;
}
}
Can someone guess that what is the error ? I can post code as well if required.
Thanks
This is from our application.ini
resources.mail.transport.type = Zend_Mail_Transport_Smtp
resources.mail.transport.host = "smtp.gmail.com"
resources.mail.transport.port = 587
resources.mail.transport.auth = "login"
resources.mail.transport.username = "email#address.com"
resources.mail.transport.password = "password"
resources.mail.transport.ssl = "tls"
And it "Just works (tm)"!
You can try with: ssl = tls or port = 587

Hacking "Contact Form 7" code to Add A "Referred By" field

I've got about 6 subdomains that have a "contact us" link and I'm sending all these links to a single form that uses "Contact Form 7". I add ?from=site-name to each of the links so that I can set a $referredFrom variable in the contact form.
The only two things I'm missing are (1) the ability to insert this referredFrom variable into the email that I get whenever someone submits the form and (2) The ability to redirect the user back to the site they came from (stored in $referredFrom)
Any ideas?
Here's a bit of code from includes/classes.php that I thought might be part of the email insert but its not doing much...
function mail() {
global $referrer;
$refferedfrom = $referrer; //HERE IS MY CUSTOM CODE
$fes = $this->form_scan_shortcode();
foreach ( $fes as $fe ) {
$name = $fe['name'];
$pipes = $fe['pipes'];
if ( empty( $name ) )
continue;
$value = $_POST[$name];
if ( WPCF7_USE_PIPE && is_a( $pipes, 'WPCF7_Pipes' ) && ! $pipes->zero() ) {
if ( is_array( $value) ) {
$new_value = array();
foreach ( $value as $v ) {
$new_value[] = $pipes->do_pipe( $v );
}
$value = $new_value;
} else {
$value = $pipes->do_pipe( $value );
}
}
$this->posted_data[$name] = $value;
$this->posted_data[$refferedfrom] = $referrer; //HERE IS MY CUSTOM CODE
}
I'm also thinking that I could insert the referredFrom code somewhere in this function as well...
function compose_and_send_mail( $mail_template ) {
$regex = '/\[\s*([a-zA-Z][0-9a-zA-Z:._-]*)\s*\]/';
$callback = array( &$this, 'mail_callback' );
$mail_subject = preg_replace_callback( $regex, $callback, $mail_template['subject'] );
$mail_sender = preg_replace_callback( $regex, $callback, $mail_template['sender'] );
$mail_body = preg_replace_callback( $regex, $callback, $mail_template['body'] );
$mail_recipient = preg_replace_callback( $regex, $callback, $mail_template['recipient'] );
$mail_headers = "From: $mail_sender\n";
if ( $mail_template['use_html'] )
$mail_headers .= "Content-Type: text/html\n";
$mail_additional_headers = preg_replace_callback( $regex, $callback,
$mail_template['additional_headers'] );
$mail_headers .= trim( $mail_additional_headers ) . "\n";
if ( $this->uploaded_files ) {
$for_this_mail = array();
foreach ( $this->uploaded_files as $name => $path ) {
if ( false === strpos( $mail_template['attachments'], "[${name}]" ) )
continue;
$for_this_mail[] = $path;
}
return #wp_mail( $mail_recipient, $mail_subject, $mail_body, $mail_headers,
$for_this_mail );
} else {
return #wp_mail( $mail_recipient, $mail_subject, $mail_body, $mail_headers );
}
}
I'd found a plugin that works fantastic for doing this, plus a little more:
http://wordpress.org/plugins/contact-form-7-leads-tracking/
Which will add all the information to the end of your email when it is sent
First of all, in order to get the from variable you'll have to insert
$referrer = $_GET['from'];
somewhere in the top script, at least before the last line you inserted.
Additionally, in the second script you have to add the value to $mail_body somehow, but since I don't know how that value is made up I can't help much with that.
Is the code for this form available online somewhere?
Insert in your functions.php or create a simple plugin...
1.
function custom_wpcf7_special_mail_tag( $output, $name ) {
if ( 'from' == $name ) {
$referredFrom = ( isset($_GET["from"]) && !empty($_GET["from"]) ) ? $_GET["from"] : '';
$output = $referredFrom;
}
return $output;
}
add_filter( 'wpcf7_special_mail_tags', 'custom_wpcf7_special_mail_tag', 10, 2 );
Use the [from] tag in your email template.
2.
function add_custom_js_cf7() {
$referredFrom = ( isset($_GET["from"]) && !empty($_GET["from"]) ) ? $_GET["from"] : '';
if ( $referredFrom ) {
?>
<script type="text/javascript">
var from = "<?php echo $referredFrom; ?>";
</script>
<?php }
}
add_action( 'wpcf7_enqueue_scripts', 'add_custom_js_cf7' );
And add this line to the "additional settings" in your form settings:
on_sent_ok: "location = from;"
http://contactform7.com/blog/2010/03/27/redirecting-to-another-url-after-submissions/
You can also use global $referredFrom; if you declared it somewhere.

Categories