Equal sign in javascript mailto url getting parsed on Android - javascript

I have a web app that sends a URL link in the body of the email from a button onclick="email();". The url is a php page with .php?id= and everything after equal sign is getting truncated when sent from an Android device.
I have tried encoding the URL but nothing is working...
I know the mailto tag uses the = sign as a parsing character...but still cannot figure this out.
Here is code.
function email() {
window.location.href = "mailto:?subject=LIVE link!&body=Here is a link for a LIVE demo!%0D%0Awww.domain.ca/scores/" + sport + "php%3Fid%3d" + id +"%0D%0A%0D%0AThanks";
}
Any suggestions or experience in this?
Works fine on all other platforms (iOS, Windows etc)

Turns out is was specific to Outlook app on Android device.

This is from one of my sites..
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['mail'];
$message = $_POST['appointment'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'Client';//<== update the email address
$email_subject = "Booking an appointment";
$email_body = "You have received a new message from the user $name.\n"."Here
is the message:\n $message";
$to = "somebody#hotmail.com ";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: aboutUs.html');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>

Related

Joomla 3.x Contact Form - Automatic Email Edits

Please be aware I am not very familiar with JavaScript and I am doing this to help out a coworker.
I am trying to make an edit to the contact form automatic email replies. The change I am looking to make is when a person sends an email to someone on the website a reply is sent back to the person stating "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME." The person receiving the email only gets the name of the person that sent it and the message.
I need to add the "This is a copy of the following message you sent to WEBSITE PERSON via WEBSITE NAME" message to the other email because one person is receiving all emails and sending them to the appropriate person. I know, this sounds unreasonable but it is what has been requested.
I found the code in contact.php but I am not entirely sure how to make the change.
This is where the code is getting the portion that I need:
// Check whether email copy function activated
if ($copy_email_activated == true && !empty($data['contact_email_copy']))
{
$copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename);
$copytext .= "\r\n\r\n" . $body;
$copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
$mail = JFactory::getMailer();
$mail->addRecipient($email);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($copysubject);
$mail->setBody($copytext);
$sent = $mail->Send();
}
return $sent;
}
}
And I need the above to work with
// Prepare email body
$prefix = JText::sprintf('COM_CONTACT_ENQUIRY_TEXT', JUri::base());
$body = $prefix . "\n" . $name . ' <' . $email . '>' . "\r\n\r\n" . stripslashes($body);
// Load the custom fields
if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields']))
{
$output = FieldsHelper::render(
'com_contact.mail',
'fields.render',
array(
'context' => 'com_contact.mail',
'item' => $contact,
'fields' => $fields,
)
);
if ($output)
{
$body .= "\r\n\r\n" . $output;
}
}
$mail = JFactory::getMailer();
$mail->addRecipient($contact->email_to);
$mail->addReplyTo($email, $name);
$mail->setSender(array($mailfrom, $fromname));
$mail->setSubject($sitename . ': ' . $subject);
$mail->setBody($body);
$sent = $mail->Send();
I thought it would be as simple as copying some code around but I am was very wrong. I knwo there are overrides in Joomla to prevent core code from being touched. As soon as I can get this figured out I can do the override to properly add my changes.
Thank you in advance!
Sorry, i used mobile so it hard to check
// Check whether email copy function activated if ($copy_email_activated == true && !empty($data['contact_email_copy'])) { $copytext = JText::sprintf('COM_CONTACT_COPYTEXT_OF', $contact->name, $sitename); $copytext .= "\r\n\r\n" . $body; $copysubject = JText::sprintf('COM_CONTACT_COPYSUBJECT_OF', $subject);
// Load the custom fields if (!empty($data['com_fields']) && $fields = FieldsHelper::getFields('com_contact.mail', $contact->email_to, true, $data['com_fields'])) { $output = FieldsHelper::render( 'com_contact.mail', 'fields.render', array( 'context' => 'com_contact.mail', 'item' => $contact, 'fields' => $fields, ) ); if ($output) { $copytext .= "\r\n\r\n" . $output; } }
$mail = JFactory::getMailer(); $mail->addRecipient($email); $mail->addReplyTo($email, $name); $mail->setSender(array($mailfrom, $fromname)); $mail->setSubject($copysubject); $mail->setBody($copytext); $sent = $mail->Send(); } return $sent; } }

How do I make a php contact form? [duplicate]

I am using PHP on a website and I want to add emailing functionality.
I have WampServer installed.
How do I send an email using PHP?
It's possible using PHP's mail() function. Remember the mail function will not work on a local server.
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
Reference:
mail
You could also use PHPMailer class at https://github.com/PHPMailer/PHPMailer .
It allows you to use the mail function or use an smtp server transparently. It also handles HTML based emails and attachments so you don't have to write your own implementation.
The class is stable and it is used by many other projects like Drupal, SugarCRM, Yii, and Joomla!
Here is an example from the page above:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
If you are interested in html formatted email, make sure to pass Content-type: text/html; in the header. Example:
// multiple recipients
$to = 'aidan#example.com' . ', '; // note the comma
$to .= 'wez#example.com';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mail function.
Also look into the PEAR mail package Pear Mail Page
It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).
Here is an excerpt from this page showing how it is used. PEAR Mail send() usage
<?php
include('Mail.php');
$recipients = 'joe#example.com';
$headers['From'] = 'richard#example.com';
$headers['To'] = 'joe#example.com';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$smtpinfo["host"] = "smtp.server.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtp_user";
$smtpinfo["password"] = "smtp_password";
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $body);
?>
For most projects, I use Swift mailer these days. It's a very flexible and elegant object-oriented approach to sending emails, created by the same people who gave us the popular Symfony framework and Twig template engine.
Basic usage :
require 'mail/swift_required.php';
$message = Swift_Message::newInstance()
// The subject of your email
->setSubject('Jane Doe sends you a message')
// The from address(es)
->setFrom(array('jane.doe#gmail.com' => 'Jane Doe'))
// The to address(es)
->setTo(array('frank.stevens#gmail.com' => 'Frank Stevens'))
// Here, you put the content of your email
->setBody('<h3>New message</h3><p>Here goes the rest of my message</p>', 'text/html');
if (Swift_Mailer::newInstance(Swift_MailTransport::newInstance())->send($message)) {
echo json_encode([
"status" => "OK",
"message" => 'Your message has been sent!'
], JSON_PRETTY_PRINT);
} else {
echo json_encode([
"status" => "error",
"message" => 'Oops! Something went wrong!'
], JSON_PRETTY_PRINT);
}
See the official documentation for more info on how to use Swift mailer.
The core way to send emails from PHP is to use its built in mail() function, but there are a couple of ready-to-use SDKs which can ease the integration:
Swiftmailer
PHPMailer
Pepipost (works over HTTP hence SMTP port block issue can be avoided)
Sendmail
P.S. I am employed with Pepipost.
For future readers: Try this if other answers don't work (As was the case with me):
1.) Download PHPMailer, open the zip file and extract the folder to your project directory.
3.) Rename the extracted directory to PHPMailer and write the below code inside of your php script (the script must be outside of the PHPMailer folder)
<?php
// PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Base files
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
// create object of PHPMailer class with boolean parameter which sets/unsets exception.
$mail = new PHPMailer(true);
try {
$mail->isSMTP(); // using SMTP protocol
$mail->Host = 'smtp.gmail.com'; // SMTP host as gmail
$mail->SMTPAuth = true; // enable smtp authentication
$mail->Username = 'sender#gmail.com'; // sender gmail host
$mail->Password = 'password'; // sender gmail host password
$mail->SMTPSecure = 'tls'; // for encrypted connection
$mail->Port = 587; // port for SMTP
$mail->setFrom('sender#gmail.com', "Sender"); // sender's email and name
$mail->addAddress('receiver#gmail.com', "Receiver"); // receiver's email and name
$mail->Subject = 'Test subject';
$mail->Body = 'Test body';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) { // handle error.
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
Try this:
<?php
$to = "somebody#example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$txt,$headers);
?>
this is very basic method to send plain text email using mail function.
<?php
$to = 'SomeOtherEmailAddress#Domain.com';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <SomeEmailAddress#Domain.com>";
mail($to,$subject,$message,$from);
The native PHP function mail() does not work for me. It issues the message:
503 This mail server requires authentication when attempting to send
to a non-local e-mail address
So, I usually use PHPMailer package
I've downloaded the version 5.2.23 from: GitHub.
I've just picked 2 files and put them in my source PHP root
class.phpmailer.php
class.smtp.php
In PHP, the file needs to be added
require_once('class.smtp.php');
require_once('class.phpmailer.php');
After this, it's just code:
require_once('class.smtp.php');
require_once('class.phpmailer.php');
...
//----------------------------------------------
// Send an e-mail. Returns true if successful
//
// $to - destination
// $nameto - destination name
// $subject - e-mail subject
// $message - HTML e-mail body
// altmess - text alternative for HTML.
//----------------------------------------------
function sendmail($to,$nameto,$subject,$message,$altmess) {
$from = "yourcontact#yourdomain.com";
$namefrom = "yourname";
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP(); // by SMTP
$mail->SMTPAuth = true; // user and password
$mail->Host = "localhost";
$mail->Port = 25;
$mail->Username = $from;
$mail->Password = "yourpassword";
$mail->SMTPSecure = ""; // options: 'ssl', 'tls' , ''
$mail->setFrom($from,$namefrom); // From (origin)
$mail->addCC($from,$namefrom); // There is also addBCC
$mail->Subject = $subject;
$mail->AltBody = $altmess;
$mail->Body = $message;
$mail->isHTML(); // Set HTML type
//$mail->addAttachment("attachment");
$mail->addAddress($to, $nameto);
return $mail->send();
}
It works like a charm
Full code example..
Try it once..
<?php
// Multiple recipients
$to = 'johny#example.com, sally#example.com'; // note the comma
// Subject
$subject = 'Birthday Reminders for August';
// Message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Johny</td><td>10th</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <mary#example.com>, Kelly <kelly#example.com>';
$headers[] = 'From: Birthday Reminder <birthday#example.com>';
$headers[] = 'Cc: birthdayarchive#example.com';
$headers[] = 'Bcc: birthdaycheck#example.com';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
You can use a mail web service such as Postmark, Sendgrid etc.
Sendgrid vs Postmark vs Amazon SES and other email/SMTP API providers?
Edit: I just use the Google Gmail API now. I had trouble sending reminder email to my employer's organization due to strict filters. But Gmail works as long as you don't spam people.
Sent the Email with this script
<h2>Test Mail</h2>
<?php
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Click To send mail">
</form>
<?php
}
else
{
if (isset($_POST["from"]))
{
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
$message = wordwrap($message, 70);
mail("Test#example.com",$subject,$message,"From: $from\n");
echo "Thank you for sending an email";
}
}
?>
Once you press the Send email button, the email will be sent to Test#example.com
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
$email_id = $params->email_id;
$flag=false;
echo "something";
if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
{
$response['ERROR']='EMAIL address format error';
echo json_encode($response,JSON_UNESCAPED_SLASHES);
return;
}
$sql="SELECT * from sales where email_id ='$email_id' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$to = "demo#gmail.com";
$subject = "DEMO Subject";
$messageBody ="demo message .";
if($count ==0){
$response["valid"] = false;
$response["message"] = "User is not registered yet";
echo json_encode($response);
return;
}
else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // authentication enabled
$mail->IsHTML(true);
$mail->SMTPSecure = 'ssl';//turn on to send html email
// $mail->Host = "ssl://smtp.zoho.com";
$mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail
$mail->Port = 465;
$mail->Username = "demousername#example.com";
$mail->Password = "demopassword";
$mail->SetFrom("demousername#example.com", "Any demo alert");
$mail->Subject = $subject;
$mail->Body = $messageBody;
$mail->AddAddress($to);
echo "yes";
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent successfully";
}
}
}
else{
$response["valid"] = false;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
The above code is working for me.
Procedure for to send a user password via email using PHPMailer :
Step 1: First, Download PHPMailer Package from GitHub
You can just download the PHPMailer source files and include the required files manually.
You can download the ZIP file with the source code from the PHPMailer homepage[1],
clicking on the “Clone or download” green button (on the right) and then selecting “Download ZIP”.
Unzip the package inside the directory where you want to save the source files.
[1] https://github.com/PHPMailer/PHPMailer
Step 2: Then, open (From Gmail Address) Google Account and do the following steps:
Disable Two factor password verification in google account.
Turn on Less Security.
Allow third party app.
Step 3: Try to use below Code (Note: Here, I have provided only the functional code for to send a user password via email using PHP and MySQL)
<?php
session_start();
use PHPMailer\PHPMailer\PHPMailer; //add use in starting of the code
$db = mysqli_connect('localhost', 'root', '', '[Enter your Database Name]'); // connect to database
if (isset($_POST['forgot_btn'])) {
forgotpassword();
}
function forgotpassword(){
global $db;
$user_id = $_POST['user_id'];
$result = mysqli_query($db,"SELECT * FROM users where user_id='$user_id'");
$row = mysqli_fetch_assoc($result);
$fetch_user_id=$row['user_id'];
$name=$row['name'];
$email_id=$row['email_id'];
$password=$row['password'];
if($user_id==$fetch_user_id) {
require '../PHPMailer/vendor/autoload.php'; //Please correctly mention the PHPMailer installed directory (Don't follow my directory)
$mail = new PHPMailer(TRUE);
try{
$mail->setFrom('[Enter your From Email_Address]', '[Enter Sender Name]');
$mail->addAddress($email_id, $name); //[To Email Address and Name]
$mail->Subject = 'Regarding Forgot Password';
$mail->Body = 'Hi '.$name.',Your Login Password is:'.$password.'';
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = 'tls';
$mail->Username = '[Enter your From Email_Address]';
$mail->Password = '[Enter your From Email_Address -> Password]';
$mail->Port = 587;
if($mail->send())
{
echo "<script>alert('Password Sent Successfully');</script>";
}
else
{
echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
}
}
catch (Exception $e)
{
echo "<script>alert('Please Check Your Internet Connection or From Email Address/Password or Wrong To Email Address');</script>";
}
}
}
?>
Refer to these docs[1] for further information:
[1]. https://alexwebdevelop.com/phpmailer-tutorial/
You can do a TESTE IF you NEED it do it through tinker as the following code
# SSH into droplet
# go to project
$ php artisan tinker
$ Mail::send('errors.401', [], function ($message) { $message->to('emmanuelbarturen#gmail.com')->subject('this works!'); });
# check your mailbox
Email with plain text
<?php
$to = 'name#example.com';
$subject = 'Your email subject here';
$message = 'Your message here';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name#example.com>".$eol;
$headers .= "Return-Path: Name <name#example.com>".$eol;
$headers .= "From: Name <name#example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/plain; charset=utf-8".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
Email with html
<?php
$to = 'name#example.com';
$subject = 'Your email subject here';
$message = '
<html>
<head>
<title>Your '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>It is a long established fact that '.$to.' reader will be distracted by the readable content of a page when looking at its layout</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name#example.com>".$eol;
$headers .= "Return-Path: Name <name#example.com>".$eol;
$headers .= "From: Name <name#example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
Email with attachment
<?php
$url = "https://c.xkcd.com/random/comic/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Must be set to true so that PHP follows any "Location:" header.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// $a will contain all headers.
$a = curl_exec($ch);
// This is what you need, it will return you the last effective URL.
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$str = file_get_contents($url.'info.0.json');
$json = json_decode($str, true);
// Get file info.
$imageTitle = $json['title'];
// Image url.
$imageUrl = $json['img'];
// Image alt text.
$imageAlt = $json['alt'];
// Image file.
$imageFile = file_get_contents($imageUrl);
$tokens = explode('/', $imageUrl);
// File name.
$fileName = $tokens[(count($tokens) - 1)];
// File extension.
$ext = explode(".", $fileName);
// File type.
$fileType = $ext[1];
// File size.
$header = get_headers($imageUrl, true);
$fileSize = $header['Content-Length'];
$to = 'name#example.com';
$subject = "Enjoy reading today's most interesting XKCD comics";
$message = '
<html>
<head>
<title>Your email '.$to.' is listed in our XKCD comics subscribers.</title>
</head>
<body>
<h1>'.$imageTitle.'</h1>
<img src='.$imageUrl.' alt='.$imageAlt.'>
</body>
</html>';
// File.
$content = chunk_split(base64_encode($imageFile));
// A random hash will be necessary to send mixed content.
$semiRand = md5(time());
$mimeBoundary = '==Multipart_Boundary_x{$semiRand}x';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = 'Reply-To: Name <name#example.com>'.$eol;
$headers .= 'Return-Path: Name <name#example.com>'.$eol;
$headers .= 'From: Name <name#example.com>'.$eol;
$headers .= 'Organization: Hostinger'.$eol;
$headers = 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"{$mimeBoundary}\"".$eol;
$headers .= 'Content-Transfer-Encoding: 7bit'.$eol;
$headers .= 'X-Priority: 3'.$eol;
$headers .= 'X-Mailer: PHP'.phpversion().$eol;
// Message.
$body = '--'.$mimeBoundary.$eol;
$body .= "Content-Type: text/html; charset=\"UTF-8\"".$eol;
$body .= 'Content-Transfer-Encoding: 7bit'.$eol;
$body .= $message.$eol;
// Attachment.
$body .= '--'.$mimeBoundary.$eol;
$body .= "Content-Type:{$fileType}; name=\"{$fileName}\"".$eol;
$body .= 'Content-Transfer-Encoding: base64'.$eol;
$body .= "Content-disposition: attachment; filename=\"{$fileName}\"".$eol;
$body .= 'X-Attachment-Id: '.rand(1000, 99999).$eol;
$body .= $content.$eol;
$body .= '--'.$mimeBoundary.'--';
$success = mail($to, $subject, $body, $headers);
if ($success === false) {
echo '<h3>Failure</h3>';
echo '<p>Failed to send email to '.$to.'</p>';
} else {
echo '<p>Your email has been sent to '.$to.' successfully.</p>';
}
Email verification
<?php
function verifyLink() {
require 'db-connection.php';
$mysqli->select_db($dbname);
$sql = "SELECT `email`, `hash` FROM `Users` ORDER BY `active`";
$result = $mysqli->query($sql);
$row = $result->fetch_row();
if ($_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] === 'on') {
return 'Verify contact email';
} else {
return 'Verify contact email';
}
$mysqli->close();
}
$to = 'name#example.com';
$subject = 'Verify your XKCD contact email address';
$message = '
<html>
<head>
<title>Verify '.$to.' as your contact email address</title>
</head>
<body>
<p>Hi, there!</p>
<p>Please verify that you want to use '.$to.' as the contact email address for your XKCD account</p>
<p>XKCD will use this email to tell you about interesting comics updates.</p>
<div>'.verifyLink().'</div>
<h3>Do not recognise this activity?</h3>
<p>If you did not add '.$to.' to your XKCD account, ignore this email and that address will not be added to your XKCD account. Someone may have made a mistake while typing their own email address.</p>
</body>
</html>
';
// Carriage return type (RFC).
$eol = "\r\n";
$headers = "Reply-To: Name <name#example.com>".$eol;
$headers .= "Return-Path: Name <name#example.com>".$eol;
$headers .= "From: Name <name#example.com>".$eol;
$headers .= "Organization: Hostinger".$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-type: text/html; charset=iso-8859-1".$eol;
$headers .= "X-Priority: 3".$eol;
$headers .= "X-Mailer: PHP".phpversion().$eol;
mail($to, $subject, $message, $headers);
I tried this in my fast time i had the same issues but after a proper resear i solved it. here is my approach. You have to download the PHPMailer source files and include the required files manually in your project.
You can download the ZIP file with the source code from the PHPMailer homepage1, clicking on the “Clone or download” green button (on the right) and then selecting “Download ZIP”. Unzip the package inside the directory where you want to save the source files.
1 from: GitHub.
Step 2: Then, open (From Gmail Address) Google Account and do the following steps:
Disable Two factor password verification in google account.
Turn on Less Security.
Allow third party app.
There you Go..
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
session_start();
if (isset($_POST['send'])) {
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = "I am trying";
//Load composer's autoloader
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'youremail#gmail.com';
$mail->Password = 'password';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//Send Email
$mail->setFrom('youremail#gmail.com');
//Recipients
$mail->addAddress($email);
$mail->addReplyTo('youremail#gmail.com');
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
$_SESSION['result'] = 'Message has been sent';
$_SESSION['status'] = 'ok';
} catch (Exception $e) {
$_SESSION['result'] = 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
$_SESSION['status'] = 'error';
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
}
header("location: forgotPassword.php");
I used this method in cPanel and everything worked fine:
<?php
$dest = "destination#domain.tld";
$fromaddy = "cpaneluser#domain.tld";
mail("<$dest>","Test from php mail","Test","From:<$fromaddy>","-f$fromaddy");
?>
$emailTextHtml='<h1>email sent from php use by phpmailer</h1>';
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
//$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'demo#gmail.com'; // SMTP username of gmail
$mail->Password = '2345678'; // SMTP password of gmail
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('anupam#gmail.com', 'study'); // provide your gmail username
$mail->addAddress('komal#gmail.com', 'study'); // Add a recipient
$mail->addReplyTo('anupamverma#gmail.com', 'Information');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Register client details and total client details';
$mail->Body= "$emailTextHtml"; //write the html code
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

JavaScript: Email login credentials to user from localStorage?

I'm wondering if it's possible to have a user click on a 'forgot password' link that will email them their password which has been set in localStorage.
I know how to set and get in localStorage, i just need to know how to email what I get to the user, who has entered his email into a form field.
Your thoughts are much appreciated. Thanks!
You are never supposed to send passwords, even to the email the user has on file. It should always be a reset password link redirect that you send. Also, localStorage isn't the proper place for information of that sort. You are going to want to implement a database to achieve the information protection you're looking for.
Localstorage works a lot like cookies. (but they are not the same)
Don't get me wrong localstorage was a phenominal update for modern browsers. Now, developers can easily load massive applications without having to store chunks in files on the server! It is advised not to store secure information such as a users password in the localstorage.
Instead generate a random MD5 hash key set up as an authorizing key for a script.
Have a script in PHP set up to return a password for an account associated with the authorizing key & username. Remember to reset the key after to authorization is made.
Database:
| ID | Username | Password | Email | Key |
| 1 | John | secret | john#gmail.com | 0cc175b9c0f1b6a831c399e269772661 |
For your PHP i would recommend you look into PHP::PDO http://php.net/manual/en/book.pdo.php
PHP: (forgot_password.php)
<?PHP
if(isset($_GET['key']) && isset($_GET['username'])){
$connect = new PDO('mysql:host=localhost;dbname=' . /* DB NAME */,/*DB USERNAME*/, /* DB PASSWORD */);
$user = getall($connect, /* TABLE NAME */,
array(
'PASSWORD'
),
array(
'key'=>$_GET['key'],
'username', $_GET['username']
), 1,
array(
'ASC'=>'ID'
);
);
print_r($user); // i will print so you can figure out how to use this for your needs
$connect = null; //close connection
}
function getall($connect, $table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = $connect->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
?>
When a user clicks the forgot password have them type in their username and email a link to the email on file with the associated user:
http://www.example.com/forgot_password.php?username=John&key=0cc175b9c0f1b6a831c399e269772661
Side note
It is Highly insecure to store passwords without hashing (many call this encryption but hashing and Encryption are entirely different) I suggest you store your passwords using password_hash read more at: http://php.net/manual/en/function.password-hash.php
I advise making the user change their password once they are authorized on the forgot_password.php script.
Your question asked how to send an email.
In order to send emails from your server you need to make sure your apache settings are configured correctly. Here is a post on stackoverflow that addresses this locally: send mail from local apache server
Once your configuration is set up correctly you can run this php function:
function send_email($subject, $msg, $to, $from){
$from - strip_tags($from);
$to = strip_tags($to);
$message = $msg;
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "X-Confirm-Reading-To:" . $from . "\r\n";
$headers .= "Mailed-By:" . $from . "\r\n";
$headers .= "Disposition-Notification-To:" . $from . "\r\n";
$headers .= "Return-Receipt-To:" . $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail( $to, $subject, $message, $headers ))
return true;
return false
}
I also want to add that if you are hoping to save a users login information this is done over the server and not on the client side. Append your form with a remember me check box. Have your PHP check if the text box is checked, if it is then store the users ID in a database table for remembered users.
You should also make PHP store at least 5 random unique hashes into a cookies, to server as a key for accessing the remembered information. Have our website check to see if the cookies exist & if they do match them up with your database table & pull the user id.

I want an alert box after form submit not redirect to thank-you.html

I am wanting say thanks in an alert box instead of redirecting to thank-you.html
Here is my code:
<?php
if (!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$contact = $_POST['contact']$message = $_POST['message'];
//Validate first
if (empty($name) || empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
if (IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
$email_from = 'tom#amazing-designs.com'; //<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n" . "Here is the message:\n $message" .
$to = "tom#amazing-designs.com"; //<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to, $email_subject, $email_body, $headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');
I do not want to redirect page to thank-you.html. I only want to show the alert with "thanks".
Remove header('Location: thank-you.html'); and add javascript
<script>
alert('Thank you!!!');
</script>
Replace header() part with:
printf("<script> alert('Thank You!'); </script>");

"Submit" button sends mail but doesn't redirect?

This script is driving me up the wall. It's a simple submission form. I click the "submit" button and the email with all the submitted information is generated perfectly fine.
But I can't get the button to then redirect me to the "Thank You" page.
I've tried PHP, I've tried Javascript, I've even tried good old fashioned Meta Redirect. Nothing works.
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
header("location:http://amvleague.vitaminh.info/thankyou.html")
}
die();
?>
I've tried putting the "header" part at the top of the document. I've tried changing it to:
echo '<script>document.location="page2.html"; </script>';
I've generated so many emails with this script that gmail is now sending them all to spam. And I can't get the damn thing to redirect.
If anyone can help before I claw my eyes out, it would be much obliged. ^_^;;
EDIT: I've tried everything you've all suggested. It's as if the script just flat-out refuses to execute anything that comes after the mail command. Could there be a reason for this?
EDIT 2: Still nothing's working.
Here's the entire script (with Rolen Koh's modifications). Is there something hidden in here that is preventing the script from accessing anything that comes after the mail tag?
<?php
if(isset($_POST['email'])) {
$email_to = "pathos#vitaminh.info";
$email_subject = "BelleCON 2014 - AMV League Submission";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['handle']) ||
!isset($_POST['amv_title']) ||
!isset($_POST['amv_song']) ||
!isset($_POST['amv_artist']) ||
!isset($_POST['amv_anime']) ||
!isset($_POST['amv_link']) ||
!isset($_POST['amv_category']) ||
!isset($_POST['email'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$handle = $_POST['handle']; // not required
$amv_title = $_POST['amv_title']; // required
$amv_song = $_POST['amv_song']; // required
$amv_artist = $_POST['amv_artist']; // required
$amv_anime = $_POST['amv_anime']; // required
$amv_link = $_POST['amv_link']; // required
$amv_category = $_POST['amv_category']; // required
$email_from = $_POST['email']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($first_name).clean_string($last_name)."\n";
$email_message .= "Handle: ".clean_string($handle)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Title of AMV: ".clean_string($amv_title)."\n";
$email_message .= "Category: ".clean_string($amv_category)."\n";
$email_message .= "Song: ".clean_string($amv_song)." by ".clean_string($amv_artist)."\n";
$email_message .= "Anime Used: ".clean_string($amv_anime)."\n\n";
$email_message .= clean_string($amv_link)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
}
}
?>
You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).
try this,this is what I am using
function redirect($url){
if (headers_sent()){
die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
}else{
header('Location: ' . $url);
die();
}
}
Try this:
$mail = mail($email_to, $email_subject, $email_message, $headers);
if($mail)
{
header("location:http://amvleague.vitaminh.info/thankyou.html");
}
Also semi-colon is missing in your header("location:http://amvleague.vitaminh.info/thankyou.html") line but i guess it is typo error.
use location.href
echo '<script>window.location.href="page2.html"; </script>';
The window.location object can be written without the window prefix.
The line
header("location:http://amvleague.vitaminh.info/thankyou.html")
Needs to be
header("Location: http://amvleague.vitaminh.info/thankyou.html");
Note the capital "L", the space after the colon, and the semicolon at the end.
If this does not resolve your issue, then you have an issue in some other piece of code. To find it, you might try looking at the php error log. If you have access to the server, you can find this by using any of the following resources for your particular server.
http://www.cyberciti.biz/faq/error_log-defines-file-where-script-errors-logged/
Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
Where can I find error log files?
If you are on a shared host, they might have some non-standard location for this file, in which case, it might be easiest to contact them and ask where their standard location of the php error log is.

Categories

Resources