I am creating a free forwarding email address system and asked a little while ago about this. What I would like to do is forward an email to the persons real email address while keeping the headers intact. Is there any reason why the below code would not work:
#!/usr/bin/php -q
<?php
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
$lines = explode("\n", $email);
$to = "";
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
$beforecheck = str_ireplace("to:", "", $to);
$checkdatabase = str_ireplace("#virtualparalegal.com", "", $beforecheck);
mysql_connect("localhost", "virtucb3_admin", "Instant11!") or
die("Could not connect to the Database, the Database returned this error: " . mysql_error());
mysql_select_db("virtucb3_wordpress");
$result = mysql_query("SELECT user_nicename, user_email FROM wp_users WHERE `user_nicename` = $checkdatabase");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ( $row["user_nicename"] == "$checkdatabase") {
$to = ($row["user_email"]);
}
else {
$to = "info#virtualparalegal.com";
}
}
for ($i=0; $i<count($lines); $i++) {
if ($splittingheaders) {
$headers .= $lines[$i]."\n";
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
$splittingheaders = false;
}
}
mail($to, $subject, $message, $headers);
?>
Thank you all in advance.
Related
Any time i use a variable for $to, the message isn't sent, and when i use "" for the email directly, it is sent. Below is my code...
$snd = "mail#mail.com";
$to = $snd; // this is your Email address
$from = $frome; // this is the sender's Email address
$titl = $title;
$subject = "Quotes From Eagle";
$message = $titl . " " . $quote;
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
But when i use the below, it is sent.
$to = "mail#mail.com"; // this is your Email address
$from = $frome; // this is the sender's Email address
$titl = $title;
$subject = "Quotes From Eagle";
$message = $titl . " " . $quote;
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
where am I getting this wrong?.
Thanks
I have tried to add a proxy server to the following perl script:
#!/usr/bin/perl
TO='list of email adresses here';
require "/usr/local/SCRIPTS/www-tools/service-name/jcode.pl";
use LWP::UserAgent;
$sendmail = '/usr/lib/sendmail -t -oi';
######################
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year = $year+1900;
$mon = $mon+1;
$MMDD = sprintf("%02d/%02d",$mon,$mday);
$HHMM = sprintf("%02d:%02d",$hour,$min);
$err = 0;
#Ph.1 WebAccess-1stServer(VIP)
#ret = &SiteAccess( 'http://IP:PORT/hostname/' ,
'http://IP:PORT/hostname/Login.do' );
if( $ret[0] != 200 || $ret[2] != 200 ){
$err = 1;
}
$body = &jcode::euc($ret[1]);
if( $body !~ m#<title>ServiceName<\/title># ){
$err = 2;
}
$title = &jcode::euc('<title>web$BO"7H(J</title>');
$body = &jcode::euc($ret[3]);
if( $body !~ m#$title# ){
$err = 3;
}
&MailSend('Web') if( $err > 0 );
$err=0;
#Ph.2 WebAccess-2ndServer(Direct)
#ret = &SiteAccess( 'http://2ndServerIP:PORT/hostname/' ,
'http://2ndServerIP:PORT/hostname/Login.do' );
if( $ret[0] != 200 || $ret[2] != 200 ){
$err = 4;
}
$body = &jcode::euc($ret[1]);
if( $body !~ m#<title>ServiceName<\/title># ){
$err = 5;
}
$title = &jcode::euc('<title>web$BO"7H(J</title>');
$body = &jcode::euc($ret[3]);
if( $body !~ m#$title# ){
$err = 6;
}
&MailSend('Web2nd') if( $err > 0);
$err=0;
#Ph.3 POP
#ret = &SiteAccess( 'http://IP:PORT/hostname/' ,
'http://IP:PORT/hostname/Login.do' );
if( $ret[0] != 200 || $ret[2] != 200 ){
$err = 7;
}
$body = &jcode::euc($ret[1]);
if( $body !~ m#<title>ServiceName</title># ){
$err = 8;
}
$title = &jcode::euc('<title>TitleJapanese<(J</title>');
$body = &jcode::euc($ret[3]);
if( $body !~ m#$title# ){
$err = 9;
}
&MailSend('POP') if( $err > 0);
$err=0;
#Ph.4 Exchange(EWS)
#ret = &SiteAccess( 'http://IP:PORT/hostname/' ,
'http://IP:PORT/hostname/Login.do' );
if( $ret[0] != 200 || $ret[2] != 200 ){
$err = 10;
}
$body = &jcode::euc($ret[1]);
if( $body !~ m#<title>ServiceName</title># ){
$err = 11;
}
$title = &jcode::euc('<title>TitleJapanese<(J</title>');
$body = &jcode::euc($ret[3]);
if( $body !~ m#$title# ){
$err = 12;
}
&MailSend('Exchange-EWS') if( $err > 0);
$err=0;
sub SiteAccess{
my $url1 = shift;
my $url2 = shift;
# $ua,$req,$res;i
my #r;
if($url1 ne ''){
$ua = LWP::UserAgent->new;
$req = HTTP::Request->new(GET => $url1);
$res = $ua->request($req);
$r[0] = $res->code;
$r[1] = $res->content;
}
if($url2 ne ''){
$ua = LWP::UserAgent->new;
$res = $ua->post( $url2,
{
"c" => "don't knwo what that is",
"u" => "users ldap",
"p" => "password"
},
"Content-Type" => "application/x-www-form-urlencoded",
"User-Agent" => "DoCoMo/2.0 N901iS(c100;TB;W24H12;ser123445654654645;icc898114564645667716666f)");
$r[2] = $res->code;
$r[3] = $res->content;
}
return #r;
}
sub MailSend{
my $title = shift;
my $body;
my $from;
my #message;
#the following lines need another file name jcode to display properly. It just means error code or auth error.
$message[1] = &jcode::jis('[Web]$B%(%i!<%3!<%I(J');
$message[4] = &jcode::jis('[Web2nd]$B%(%i!<%3!<%I(J');
$message[7] = &jcode::jis('[POP]$B%(%i!<%3!<%I(J');
$message[10] = &jcode::jis('[EWS]$B%(%i!<%3!<%I(J');
$message[2] = &jcode::jis('[Web]$B%m%0%$%s2hLL(J');
$message[5] = &jcode::jis('[Web2nd]$B%m%0%$%s2hLL(J');
$message[8] = &jcode::jis('[POP]$B%m%0%$%s2hLL(J');
$message[11] = &jcode::jis('[EWS]$B%m%0%$%s2hLL(J');
$message[3] = &jcode::jis('[Web]auth$B%(%i!<(J');
$message[6] = &jcode::jis('[Web2nd]auth$B%(%i!<(J');
$message[9] = &jcode::jis('[POP]auth$B%(%i!<(J');
$message[12] = &jcode::jis('[EWS]auth$B%(%i!<(J');
$from = 'mail#abc.com';
$title = '['.$title.']cnct1 err';
# $title = $title.'['.$MMDD.$HHMM.']';
$body =<<END_OF_BODY;
To: $TO
Subject: $title
From: $from
ConnectOneCheck Error
Date : $MMDD $HHMM
ErrorStatus: $err
ErrorMsg : $message[$err]
END_OF_BODY
open(ML,"| $sendmail") || &error("Can't execute sendmail : $sendmail\n");
print ML $body;
close(ML);
}
So now here's the part where I tried to add the usage of a proxy. Most parts are commented out, except for the last function:
!/usr/bin/perl
TO='list of email adresses here';
require "/usr/local/SCRIPTS/www-tools/service-name/jcode.pl";
use LWP::UserAgent;
$sendmail = '/usr/lib/sendmail -t -oi';
######################
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year = $year+1900;
$mon = $mon+1;
$MMDD = sprintf("%02d/%02d",$mon,$mday);
$HHMM = sprintf("%02d:%02d",$hour,$min);
$err = 0;
The next part is commented out because it is not in use.
#ret = &SiteAccess( 'http://IP:PORT/hostname/' ,
'http://IP:PORT/hostname/Login.do' );
if( $ret[0] != 200 || $ret[2] != 200 ){
$err = 10;
}
$body = &jcode::euc($ret[1]);
if( $body !‾ m#<title>ConnectONE</title># ){
$err = 11;
}
$title = &jcode::euc('<title>TitleJapanese</title>');
$body = &jcode::euc($ret[3]);
if( $body !‾ m#$title# ){
$err = 12;
}
&MailSend('Exchange-EWS') if( $err > 0);
$err=0;
sub SiteAccess{
my $url1 = shift;
my $url2 = shift;
# $ua,$req,$res;i
my #r;
if($url1 ne ''){
$ua = LWP::UserAgent->new;
$ENV{HTTP_proxy} = "proxy fqdn here";
$ua->env_proxy
$req = HTTP::Request->new(GET => $url1);
$res = $ua->request($req);
$r[0] = $res->code;
$r[1] = $res->content;
}
if($url2 ne ''){
$ua = LWP::UserAgent->new;
$ENV{HTTP_proxy} = "proxy fqdn here";
$ua->env_proxy
$res = $ua->post( $url2,
{
"c" => "don't knwo what that is",
"u" => "users ldap",
"p" => "password"
},
"Content-Type" => "application/x-www-form-urlencoded",
"User-Agent" => "DoCoMo/2.0 N901iS(c100;TB;W24H12;ser123445654654645;icc898114564645667716666f)");
$r[2] = $res->code;
$r[3] = $res->content;
}
return #r;
}
sub MailSend{
my $title = shift;
my $body;
my $from;
my #message;
#the following lines need another file name jcode to display properly. It just means error code or auth error.
#$message[1] = &jcode::jis('[Web]$B%(%i!<%3!<%I(J');
#$message[4] = &jcode::jis('[Web2nd]$B%(%i!<%3!<%I(J');
#$message[7] = &jcode::jis('[POP]$B%(%i!<%3!<%I(J');
$message[10] = &jcode::jis('[EWS]$B%(%i!<%3!<%I(J');
#$message[2] = &jcode::jis('[Web]$B%m%0%$%s2hLL(J');
#$message[5] = &jcode::jis('[Web2nd]$B%m%0%$%s2hLL(J');
#$message[8] = &jcode::jis('[POP]$B%m%0%$%s2hLL(J');
$message[11] = &jcode::jis('[EWS]$B%m%0%$%s2hLL(J');
#$message[3] = &jcode::jis('[Web]auth$B%(%i!<(J');
#$message[6] = &jcode::jis('[Web2nd]auth$B%(%i!<(J');
#$message[9] = &jcode::jis('[POP]auth$B%(%i!<(J');
$message[12] = &jcode::jis('[EWS]auth$B%(%i!<(J');
$from = 'mail#abc.com';
$title = '['.$title.']cnct1 err';
# $title = $title.'['.$MMDD.$HHMM.']';
$body =<<END_OF_BODY;
To: $TO
Subject: $title
From: $from
ConnectOneCheck Error
Date : $MMDD $HHMM
ErrorStatus: $err
ErrorMsg : $message[$err]
END_OF_BODY
open(ML,"| $sendmail") || &error("Can't execute sendmail : $sendmail\n");
print ML $body;
close(ML);
}
OK so I have added a proxy using this function
$ua = LWP::UserAgent->new;
$ENV{HTTP_proxy} = "here is the FQDN of the proxy";
$ua->env_proxy
But it doesn't compile well. It gives me this error:
syntax error at /usr/local/SCRIPTS/www-tools/connectone/ConnectOneCheck.pl line 93, near "$body !"
Unrecognized character \xE2; marked by <-- HERE after f( $body !<-- HERE near column 12 at /usr/local/SCRIPTS/www-tools/connectone/ConnectOneCheck.pl line 93.
Is here someone who can get this script running?
Your script does not compile as it is presented here. In Line 3 where it says
TO='list of
it needs to be changed to
$TO='list of
...and then it compiles for me. Without the error you are getting in line 93.
From my limited viewpoint this means there may actually be some misprint in your code line 93 that did not make it to the code on this side.
If you erase your line 93 in your script and copy the line 93 back into your code, you might be settled.
You have a non-ASCII character OVERLINE (U+203E) (‾) in your source code, and that is the cause of the error you have shown.
The first code point of Unicode characters in the U+2000–206F "General Punctuation" block is \xE2. That was the first clue. The overline is 0xE2 0x80 0xBE in hex.
Perhaps there was some encoding problem that translated the tildes (~) in those few places in your original source into these overlines.
You may also see errors like this when “curly” quotes, en (–) and em (—) dashes, and the like have crept into your source code. Sometimes it's due to well-meaning software such as WordPress or MS Word automatically substituting, for example, straight for curly quotes, which you in turn copy-pasted into your source code.
It's difficult to spot these visually (I didn't notice the overline at first), but this shell one-liner strips characters in the non-ASCII range and then compares side-by-side with the original file on the left:
# assumes Bash shell
sdiff --suppress-common-lines script.pl <(tr -cd '\11\12\15\40-\176' <script.pl)
A similar encoding problem in a Python context, with an error message about \xE2, is described in this SO question. This gave me the idea to look for non-ASCII characters in your source code.
I'm trying to write a page where users can send an email along with an attachment. I think I'm almost there. Right now I get the email, but the attachment is either empty in filesize, or when I try to open it, I get a message that it cannot be opened. Any help is appreciated.
function valid_email($Email)
{
//new regex, didn't give me any errors...might be a bit more exact
if (ereg('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$', $Email) != false)
return true;
else
return false;
}
function sendEmail($email){
return mail ($email['to'], $email['subject'], $email['message'], $email['headers']);
}
if ( strlen($_FILES['Resume_File']['name']) > 0 )
{ // If a file was uploaded, do some processing
$filename = preg_replace('/[^a-zA-Z0-9._-]/', '', $_FILES['Resume_File']['name']);
$filetype = $_FILES["Resume_File"]["type"];
$filesize = $_FILES["Resume_File"]["size"];
$filetemp = $_FILES["Resume_File"]["tmp_name"];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if ( !preg_match('/\.(doc|docx|odt|pdf|rtf|txt)/i', $ext) )
{ $errors++;
$errorLog .= "Upload filetype not supported.";
}
else if ( $filesize > 2000000 )
{ $errors++;
$errorLog .= "File size too high, up to 2MB is allowed.";
}
else
{ // Looks like the file is good, send it with the email
//$fp = fopen($filetemp, "rb");
//$file = fread($fp, $filesize);
//$file = chunk_split(base64_encode($file));
//$email['headers'] .= "\n--{$num}\n";
//$email['headers'] .= "Content-Type:{$filetype}";
//$email['headers'] .= "name={$filename}r\n";
//$email['headers'] .= "Content-Disposition: attachment; ";
//$email['headers'] .= "filename={$filename}\n";
//$email['headers'] .= "{$file}";
}
}
// get posted data into local variables
$fname = trim(stripslashes($_POST['fname']));
$lname = trim(stripslashes($_POST['lname']));
$emailAddress = trim(stripslashes($_POST['email']));
$company = trim(stripslashes($_POST['company']));
$information = trim(stripslashes($_POST['information']));
$subject = trim(stripslashes($_POST['subject']));
$title = trim(stripslashes($_POST['title']));
//setup email
$to = 'me#me.com';
$subject = "Resume Submission";
$headers = "From: {$fname} {$lname} <{$emailAddress}>\r\n";
// prepare email body text
$message = "First Name: {$fname} <br>";
$message .= "Last Name: {$lname} <br>";
$message .= "Email: {$emailAddress} <br>";
$message .= "Title: {$title} <br><br>";
$message .= "Comments: {$information}";
if ( $errors == 0 ) {
// Attachment headers
//$to = "myemail#mydomain.com";
//$from = "Website <website#mydomain.com>";
//$subject = "Test Attachment Email";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
//$filename = "document.pdf";
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers .= "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
}
//sendEmail($email);
// validation
if ( $errors == 0 ) {
if (valid_email($emailAddress) && $fname != "" && $lname != "") { //if return is true...
mail($to, $subject, $body, $headers);
echo 0; //Success
}else { //otherwise
echo 1; //Error
}
} else {
echo 1; //Error
}
I am using portions of code which I found here
PHP mail() attachment problems
Thank you!
PHP's mail() function is really poor, particularly when trying to do advanced stuff like adding attachments. It's really only worth using for the most basic "send a notification email to the site admin" type emails, and even then it's not always the best solution.
I would suggest ditching any attempt to work with the mail() function itself, and instead switch to using a decent PHP mailer class such as the appropriately named phpMailer.
phpMailer makes creating emails from PHP dead easy. I has all the features you could want, including making it very easy to add attachments, write HTML emails, and plenty more.
But the best thing about phpMailer is that it removes all the need to waste dozens of lines of code formatting the email headers. All that stuff with the separators and mime types becomes reduced to a few simple lines of code. Easier to read, easier to maintain, and less likely to have bugs. You win all round.
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode($pdfdoc));
$pdfdoc is not mentioned any where in the page. I presume that is the issue:|
I am try to send mail through smtp server(gmail) from my localhost(wamp).When running the program it will display the Fatal error: Maximum execution time of 30 seconds exceeded .I was change the timeout gain it will produce same error
<?php
$to = "email#gmail.com";
$nameto = "Who To";
$from = "from#fast2host.com";
$namefrom = "Who From";
$subject = "Hello World Again!";
$message = "World, Hello!";
authSendEmail($from, $namefrom, $to, $nameto, $subject, $message);
function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
{
//SMTP + SERVER DETAILS
/* * * * CONFIGURATION START * * * */
$smtpServer = "smtp.gmail.com";
$port = "25";
$timeout = "30";
$username = "username";
$password = "password";
$localhost = "27.107.106.163";
$newLine = "\r\n";
/* * * * CONFIGURATION END * * * * */
//Connect to the host on the specified port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if(empty($smtpConnect))
{
$output = "Failed to connect: $smtpResponse";
return $output;
}
else
{
$logArray['connection'] = "Connected: $smtpResponse";
}
//Request Auth Login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authrequest'] = "$smtpResponse";
//Send username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authusername'] = "$smtpResponse";
//Send password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['authpassword'] = "$smtpResponse";
//Say Hello to SMTP
fputs($smtpConnect, "HELO $localhost" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['heloresponse'] = "$smtpResponse";
//Email From
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['mailfromresponse'] = "$smtpResponse";
//Email To
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['mailtoresponse'] = "$smtpResponse";
//The Email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['data1response'] = "$smtpResponse";
//Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
fputs($smtpConnect, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message \n.\n");
$smtpResponse = fgets($smtpConnect, 515);
$logArray['data2response'] = "$smtpResponse";
// Say Bye to SMTP
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 515);
$logArray['quitresponse'] = "$smtpResponse";
}
?>
Please help me anyone for debug the errors
You have too much redundant code, this is what you should do:
<?php
require_once 'Mail.php';
require_once 'Mail/mime.php';
// set all of the parameters
$to = "Who To <email#gmail.com>";
$from = "Who From <from#fast2host.com>";
$subject = "Hello World Again!";
$message = "World, Hello!";
$text = strip_tags($message);
// create the headers
$headers = array(
'Subject' => $subject,
'From' => $from,
'To' => $to,
'MIME-Version' => '1.0',
'Date' => date('r'),
'Message-ID' => '<'.sha1(microtime(true)).'#mydomain.com>',
'Content-Type' => 'text/html',
'Content-Transfer-Encoding' => 'quoted-printable',
); // end $headers
// create the message
$mime = new Mail_mime("\n");
$mime->setTXTBody($text);
$mime->setHTMLBody($message);
// always call these methods in this order
$body = $mime->get();
$headers = $mime->headers($headers);
// create the smtp mail object
$smtp_params = array(
'host' => 'smtp.gmail.com',
'auth' => true,
'username' => 'myUserName',
'password' => 'myPassWord',
); // end $smtp_params
$smtp = Mail::factory('smtp', $smtp_params);
// send the message
$recipients = array($to);
$mail = $smtp->send($recipients, $headers, $body);
?>
PS. The 'auth'=> true; in the smtp_params array flags for an ssl connection.
my $Parser = new MIME::Parser;
my $entity = $Parser->parse_data( $body );
my #parts = $entity->parts;
for $part(#parts){
my $type=$part->mime_type;
my $bhandle=$part->bodyhandle;
$header = $part->head();
$content_disp = $header->get('Content-Disposition');
if ($type =~ /text/i){
$bodydata = "";
if (my $io = $part->open("r")) {
while (defined($_ = $io->getline)) {
$bodydata .= $_;
}
$io->close;
print $bodydata;
}
}
}
I think you're looking for the recommended_filename method:
$header = $part->head();
$filename = $header->recommended_filename;
Be sure to check the return value for sanity. Note that it can also be undef.