I am having trouble with a form, when the user mail is not inserted, it always return the error message "Invalid address: email". I understand $reg_email variable is being used in other functions to send the mail to the user, so I realize I must write a condition that says that when the reg_email variable is empty, it must return a value that wont cause that error. But I dont know how to translate that logic to PHP. What should I do?
<?php
ini_set('display_errors', 1);
session_start();
if($_SESSION['input_flag']) {
unset($_SESSION['input_flag']);
}else{
header('location: /');
}
$path = realpath(dirname(__FILE__) . '') . "/../";
include_once($path.'app_config.php');
include($path.'libs/meta.php');
//設定
require('./jphpmailer.php');
$script = "index.php";
$gtime = time();
$reg_name = isset($_POST['f_name']) ? htmlspecialchars($_POST['f_name']): "";
if (isset($_POST['f_company']) && !empty($_POST['f_company'])) {
$f_company .= "■会社名"."\r\n" . $_POST['f_company'];
}
$f_adress = isset($_POST['f_adress']) ? htmlspecialchars($_POST['f_adress']): "";
$f_select = '';
if (!empty($_POST['select'])) {
foreach ($_POST['select'] as $key => $value) {
$f_select .= "設置されている消防設備"."\r\n" . $_POST['f_select'];
}
}
$f_tel = isset($_POST['f_tel']) ? htmlspecialchars($_POST['f_tel']): "";
// $reg_email = isset($_POST['f_mail']) ? htmlspecialchars($_POST['f_mail']): "";
if (isset($_POST['f_mail']) || !empty($_POST['f_mail'])) {
$reg_email .= "email"."\r\n" . $_POST['f_mail'];
}
$f_select2 = '';
foreach ($_POST['select2'] as $key => $value) {
$f_select2 .= $value."\r\n";
}
$f_request = isset($_POST['f_request']) ? htmlspecialchars($_POST['f_request']): "";
$aMailto = array(
"xxxxxx"
);
$from = "xxxxxx";
$fromname = '';
$subject1 = 'test';
$subject = 'test';
$entry_time = gmdate("Y/m/d H:i:s",time()+9*3600);
$entry_host = gethostbyaddr(getenv("REMOTE_ADDR"));
$entry_ua = getenv("HTTP_USER_AGENT");
$msgBody = "";
$msgBody .= "
■お名前
$reg_name
$f_company
■建物の所在地
$f_adress
$f_select
■お電話番号
$f_tel
$reg_email
■ご希望の連絡方法
$f_select2
■お問い合わせ内容
$f_request
";
//お問い合わせメッセージ送信
$subject = "ホームページからお問い合わせがありました";
$body = "
登録日時:$entry_time
ホスト名:$entry_host
ブラウザ:$entry_ua
ホームページからお問い合わせがありました。
$msgBody
";
//Message for the user
$subject1 = "お問い合わせありがとうございました";
$body1 = "
$reg_name 様
$msgBody
";
// メール送信
mb_language("ja");
mb_internal_encoding("UTF-8");
$fromname = "";
//お客様受け取りメール送信
$email1 = new JPHPmailer();
$email1->addTo($reg_email);
$email1->setFrom($from,$fromname);
$email1->setSubject($subject1);
$email1->setBody($body1);
//if($email1->send()) {};
//Anti spam advanced version 2 start: Don't send blank emails
if( $reg_name <> "" && $reg_email <> "" ) {
//Anti spam advanced version 1 start: The preg_match() is there to make sure spammers can’t abuse your server by injecting extra fields (such as CC and BCC) into the header.
if( $reg_email && !preg_match( "/[\r\n]/", $reg_email) ) {
//Anti spam part1: the contact form start
if($reg_url == ""){
// then send the form to your email
if($email1->Send()) {};
} // otherwise, let the spammer think that they got their message through
//Anti spam part1: the contact form end
}//Anti spam advanced version 1 end
}//Anti spam advanced version 2 end: Don't send blank emails
//メール送信
$email = new JPHPmailer();
for($i = 0; $i < count($aMailto); $i++)
{
$email->addTo($aMailto[$i]);
}
$email->setFrom($reg_email, $reg_name."様");
$email->setSubject($subject);
$email->setBody($body);
//if($email->Send()) {};
//Anti spam advanced version 2 start: Don't send blank emails
if( $reg_name <> "" && $reg_email <> "" ) {
//Anti spam part1: the contact form start
if($reg_url == ""){
// then send the form to your email
if($email->Send()) {};
} // otherwise, let the spammer think that they got their message through
//Anti spam part1: the contact form end
}//Anti spam advanced version 2 end: Don't send blank emails
?>
It's because you're doing this:
$reg_email .= "email"."\r\n" . $_POST['f_mail'];
the word email, followed by a line break, followed by an email address is not itself a valid email address, so will be rejected with the error you're seeing. You're also appending to a variable that has not yet been defined. Do this instead:
$reg_email = $_POST['f_mail'];
I'm also puzzled by this:
$email->addTo($aMailto[$i]);
PHPMailer uses addAddress, not addTo, so unless that's a new method or alias in your JPHPmailer subclass, it's wrong.
Also, don't do this:
$email->setFrom($reg_email, $reg_name."様");
This is forgery and will result in your message being bounced or spam filtered by recipients. Do this instead:
$email->setFrom('myemail#example.com', $reg_name."様");
$email->addReplyTo($reg_email, $reg_name."様");
That is, send from your own address and use the submitter's address as a reply-to.
Related
I’m having problems getting the sender's email address,
$single_message = $gmail->users_messages->get('me', $msg_id);
"from" usually yields the senders name
To get the email address I have this code
if($partes->getName() == 'Authentication-Results')
{
$outh_res = $partes->getValue();
if(strpos($outh_res, 'smtp.mailfrom=') !== false)
{
$bits = explode('smtp.mailfrom=',$outh_res);
$mail = $bits[1];
if(strpos($mail, ';') !== false)
{
$bits = explode(';',$mail);
$mail = str_replace('"', '',$bits[0]);
}
}
}
That always gives me an email, but when the sender is behind mail chimp (or their own servers (postfix)) for example: bounces+2063633-785c-info=myemail.com#sg1.senderemail.com
In the best case I receive #sendermail.com (from gmail itself I know its info#sendermail.com) so it's useless
In some cases
if($partes->getName() == 'Reply-To')
{
$other_mail = str_replace('"', '',$partes->getValue());
}
Gives me a helpful email others just the senders name
as suggested in github php gmail api issue # 521 and other places
$only_header = $gmail->users_messages->get('me',$msg_id, ['format' => 'metadata', 'metadataHeaders' => ['To','X-Original-To','X-Original-From','From','Reply-To','Subject']]);
It gives exactly the same info.
Is there any way that the api gives me exactly the sender email address even if it's behind mail chimp or other 3rd party sender?
There's a similar answer Get sender email from gmail-api, I already loop the headers and tried zingzinco's answer.
Edit: Thanks to Joey Tawadrous;
Php code:
if($partes->getName() == 'From')
{
$raw_from = $partes->getValue();
if(strpos($raw_from, '<') !== false)
{
$bit = explode('<',$raw_from);
$bit2 = explode('>',$bit[1]);
$final_email = $bit2[0];
$sender_name = str_replace('"', '',$bit[0]);
}
else
{
$sender_name = limpiarm(str_replace('"', '',$raw_from));
}
}
var email = '';
var messageFrom = _.where(message.payload.headers, {name: 'From'})[0].value;
if(messageFrom.includes('<')) {
var fromObj = messageFrom.split('<');
email = fromObj[1];
fromObj = email.split('>');
email = fromObj[0];
}
return email;
I have a php mail form with a item that is not required to be written.
This item has the variable $text, and every time a mail is sent, even if this item was not filled, a text in the body of the message will be sent.
This is the code for the body of the message:
■message
$text
and the message will look like this:
■message
Using "isset", I want to make a condition that only writes "message" text when $text is defined. As I am not familiar with php, I am doing something wrong..
$message = "message";
$text = isset($_POST[$message]) ? htmlspecialchars($_POST[$message]): "";
$message
$text
here is the original code:
<?php
ini_set('display_errors', 1);
session_start();
if($_SESSION['input_flag']) {
unset($_SESSION['input_flag']);
}else{
header('location: /');
}
$path = realpath(dirname(__FILE__) . '') . "/../";
include_once($path.'app_config.php');
include($path.'libs/meta.php');
require('./jphpmailer.php');
$script = "index.php";
$gtime = time();
//$f_name = isset($_POST['f_name']) ? htmlspecialchars($_POST['f_name']): "";
$reg_name = isset($_POST['f_name']) ? htmlspecialchars($_POST['f_name']): "";
$f_tel = isset($_POST['f_tel']) ? htmlspecialchars($_POST['f_tel']): "";
//$f_mail = isset($_POST['f_mail']) ? htmlspecialchars($_POST['f_mail']): "";
$reg_email = isset($_POST['f_mail']) ? htmlspecialchars($_POST['f_mail']): "";
$text = isset($_POST['text']) ? htmlspecialchars($_POST['text']): "";
$f_model = isset($_POST['f_model']) ? htmlspecialchars($_POST['f_model']): "";
$f_request = isset($_POST['f_request']) ? htmlspecialchars($_POST['f_request']): "";
$f_select = '';
foreach ($_POST['select'] as $key => $value) {
$f_select .= $value.'';
}
$aMailto = array(
"xxxx#xxx.com"
);
$from = "test#xxxx.com";
$fromname = 'test';
$subject1 = 'test';
$subject = 'test';
$entry_time = gmdate("Y/m/d H:i:s",time()+9*3600);
$entry_host = gethostbyaddr(getenv("REMOTE_ADDR"));
$entry_ua = getenv("HTTP_USER_AGENT");
$msgBody = "";
$msgBody .= "
■お名前
$reg_name
■お電話番号
$f_tel
■メールアドレス
$reg_email
■message
$text
■ご希望の連絡方法
$f_select
■ご希望の車種
$f_model
■お問い合わせ内容
$f_request
";
$msgBody
";
---------------------------------------------------------------
---------------------------------------------------------------
$msgBody
mb_language("ja");
mb_internal_encoding("UTF-8");
$fromname = "test";
$email1 = new JPHPmailer();
$email1->addTo($reg_email);
$email1->setFrom($from,$fromname);
$email1->setSubject($subject1);
$email1->setBody($body1);
//if($email1->send()) {};
//Anti spam advanced version 2 start: Don't send blank emails
if( $reg_name <> "" && $reg_email <> "" ) {
//Anti spam advanced version 1 start: The preg_match() is there to make sure spammers can’t abuse your server by injecting extra fields (such as CC and BCC) into the header.
if( $reg_email && !preg_match( "/[\r\n]/", $reg_email) ) {
//Anti spam part1: the contact form start
if($reg_url == ""){
// then send the form to your email
if($email1->Send()) {};
} // otherwise, let the spammer think that they got their message through
//Anti spam part1: the contact form end
}//Anti spam advanced version 1 end
}//Anti spam advanced version 2 end: Don't send blank emails
//メール送信
$email = new JPHPmailer();
for($i = 0; $i < count($aMailto); $i++)
{
$email->addTo($aMailto[$i]);
}
$email->setFrom($reg_email, $reg_name."様");
$email->setSubject($subject);
$email->setBody($body);
//if($email->Send()) {};
//Anti spam advanced version 2 start: Don't send blank emails
if( $reg_name <> "" && $reg_email <> "" ) {
//Anti spam part1: the contact form start
if($reg_url == ""){
// then send the form to your email
if($email->Send()) {};
} // otherwise, let the spammer think that they got their message through
//Anti spam part1: the contact form end
}//Anti spam advanced version 2 end: Don't send blank emails
?>
I'm trying to get this contact form working and it doesn't seem to be able to send with headers saying it is from a gmail address I feel like yahoo addresses were also in the mix of ones that didn't work. Here is the code that seems like it would matter to this. If the host matters I am on Dreamhost. Let me know please.
if(!is_array($contact_information_type))
{
$contact_information_type = Array();
}
if($_POST){
$contact_name = trim(stripslashes($_POST["contact_name"]));
$contact_company = trim(stripslashes($_POST["contact_company"]));
$contact_address1 = trim(stripslashes($_POST["contact_address1"]));
$contact_address2 = trim(stripslashes($_POST["contact_address2"]));
$contact_city = trim(stripslashes($_POST["contact_city"]));
$contact_state = trim(stripslashes($_POST["contact_state"]));
$contact_zip = trim(stripslashes($_POST["contact_zip"]));
$contact_country = trim(stripslashes($_POST["contact_country"]));
$contact_phone = trim(stripslashes($_POST["contact_phone"]));
$contact_fax = trim(stripslashes($_POST["contact_fax"]));
$contact_email = trim(stripslashes($_POST["contact_email"]));
$contact_comments = trim(stripslashes($_POST["contact_comments"]));
if($contact_name == ""){ $errors_array[] = "Name is required."; }
if($contact_company == ""){ $errors_array[] = "Company name is required."; }
if($contact_city == "") { $errors_array[] = "City is required."; }
if($contact_state == ""){ $errors_array[] = "State is required."; }
if($contact_country == "") { $errors_array[] = "Country is required.";}
elseif($contact_country == "United States" )
{if($contact_zip != "" && !preg_match("/(^\d{5}$)|(^\d{5}-\d{4}$)/", $contact_zip)){ $errors_array[] = "Incorrect Zip. (e.g. 60660 or 60660-1234)"; };}
elseif($contact_country == "Canada" ){if($contact_zip != "" && !preg_match("/^[ABCEGHJ- NPRSTVXY]{1}[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[ ]?[0-9]{1}[ABCEGHJ-NPRSTV-Z]{1}[0-9]{1}$/i", $contact_zip)){ $errors_array[] = "Incorrect Zip. (e.g. M4C 1B5 or M4C1B5)"; };}
else {;}
if($contact_phone == ""){ $errors_array[] = "Phone is required."; }
if($contact_phone != "" && !preg_match("/(^\d{3}-\d{3}-\d{4}$)| (^\d{10}$)/", $contact_phone)){ $errors_array[] = "Incorrect Phone. (e.g. 123-123-1234)"; }
if($contact_fax != "" && !preg_match("/(^\d{3}-\d{3}-\d{4}$)|(^\d{10}$)/", $contact_fax)){ $errors_array[] = "Incorrect Fax. (e.g. 123-123-1234)"; }
if($contact_email == ""){ $errors_array[] = "E-mail is required."; }
if($contact_email != "" && !preg_match("/^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+\. [a-zA-Z0-9-.]+$/", $contact_email)){ $errors_array[] = "Incorrect E-mail. (e.g. youremail#domain.com)"; }
if($contact_comments == ""){ $errors_array[] = "Comments are required."; }
if(sizeof($errors_array) == 0){
$contact_information_type = implode(", ", $contact_information_type);
$email_message = <<<MESSAGE
The contact form on www.rotaryvalve.com has been filled out with the following information:
Name: ${contact_name}
Company: ${contact_company}
Address 1: ${contact_address1}
Address 2: ${contact_address2}
City: ${contact_city}
State: ${contact_state}
Zip: ${contact_zip}
Country: ${contact_country}
Phone: ${contact_phone}
Fax: ${contact_fax}
E-mail: ${contact_email}
Comments/Products of Interest: ${contact_comments}
MESSAGE;
$email_adds = array("sales-team#wmwmeyer.com", "dan#danbaran.com");
$email_from = $contact_email;
$email_subject = "Customer Request/Comment";
foreach($email_adds as $email_to){
mail ($email_to, $email_subject, $email_message, "From: ".$email_from." <".$email_from.">");
}
essentially if the contact_email filled out on the form(code not included sorry didn't think you'd need it but let me know if you do) is a gmail account it doesn't seem to send it please help me out on this one.
Is the problem not being sent, or not being received. I'm pretty sure that the problem is not the email being sent, but what happens when it gets received by the receiver's email service. It may be classed as spam, because they can see it is not sent from the GMail mailservers.
The email may be classed as spam by the receiving server or client, due to SPF records on the gmail.com domain that will most likely mark the emails as spam.
You would however be able to send the email with a 'Reply-To' header of the email entered in the contact form. This would give the email a better chance of getting past spam filters, and if the recipient hits the "Reply" button in their client, the email will default to being sent to this address.
I have been on this for days and days, and am at the point that I have pulled out so many hairs that I now have just one hair left on my head. That hair is my last bit of pride. But seriously though, I have found dozens of answers but none seem to apply to my problem!
I have an e-mail form for a website I made. The site and form are made in Flash (AS3), the script for processing the e-mail is an external php file. The e-mail form works just fine, except for when I use certain characters:
% is not shown in the e-mail, including any text directly behind it
when a &, < or > is present, the form will say 'sending..' but not go beyond that point; I don't receive any e-mail.
All (or most at least) other characters like !##$^*_+-=~` are no problem.
I have already made sure both AS3 and php codes have
"MIME-Version: 1.0; Content-Type: text/html; charset=utf-8" is included in my sending if check in the php file;
the textfields in AS3 are set to htmlText instead of just text.
My scripts:
mail.php
if( $yourName == true ) {
$sender = $fromEmail;
$yourEmail = "myemail#example.com"; // Here i of course use my own email address
$ipAddress = $_SERVER['REMOTE_ADDR']; // This gets the user's ip Address
$emailMsg = "Van: $sender\r\n" .
"Name: $yourName\r" .
"Subject: $yourSubject\n\n" .
"$yourMsg\n\n\n\n" .
"------------------------------\r" .
"Sent from IP-address $ipAddress\r" .
"X-Mailer: PHP/" . phpversion();
# these are three (out of many) things I tried to work around the problem #
//$emailMsg = str_replace( '&', "&", $emailMsg );
//$emailMsg = htmlspecialchars($emailMsg, ENT_QUOTES);
//$emailMsg = mysql_real_escape_string($emailMsg);
$return = "From: $sender\r\n";
if( mail($yourEmail, "$yourSubject", $emailMsg, $return, "MIME-Version: 1.0; Content-Type: text/html; charset=utf-8")) {
echo "sentStatus=yes";
}
else {
echo "sentStatus=no";
}
}
?>
FormScript.as
package {
/*required imports*/
public class FormScript extends Sprite {
/*here are the variable declarations*/
public function FormScript() {
sendbtn.buttonMode = true;
sendbtn.addEventListener(MouseEvent.CLICK, submit);
resetbtn.buttonMode = true;
resetbtn.addEventListener(MouseEvent.CLICK, reset);
urlRequest.method = URLRequestMethod.POST;
/*here are are some positionings and addchilds*/
function init():void {
//Set all fields to empty
yourName.htmlText = "";
fromEmail.htmlText = "";
yourSubject.htmlText = "";
yourMsg.htmlText = "";
valid.text = "";
}
function submit(e:MouseEvent):void {
//Check to see if any of the fields are empty
if(yourName.htmlText == "" || fromEmail.htmlText == "" ||
yourSubject.htmlText == "" ||yourMsg.htmlText == "" ) {
valid.text = "All fields must be filled in";
}//Check if you're using a valid email address
else if(!checkEmail(fromEmail.htmlText)) {
valid.text = "Please enter a valid e-mail address";
}
else {
valid.text = "Sending..";
var emailData:String =
"name=" + yourName.htmlText +
"&from=" + fromEmail.htmlText +
"&subject=" + yourSubject.htmlText +
"&msg=" + yourMsg.htmlText;
var urlVars:URLVariables = new URLVariables(emailData);
urlVars.dataFormat = URLLoaderDataFormat.TEXT;
urlRequest.data = urlVars; varLoad.load( urlRequest );
varLoad.addEventListener(Event.COMPLETE, thankYou );
}
}
function reset(e:MouseEvent):void {
init(); //call the initial clear function
}
function checkEmail(s:String):Boolean {
//yourMsg.text = escape("&");
//This tests for correct email address
var p:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var r:Object = p.exec(s);
if( r == null ) {
return false;
}
return true;
}
function thankYou(e:Event):void {
var loader:URLLoader = URLLoader(e.target);
var sent = new URLVariables(loader.data).sentStatus;
//valid.text = sent;
if( sent == "yes" ) {
valid.text = "Thank you for your e-mail!"; timer = new Timer(500);
timer.addEventListener(TimerEvent.TIMER, msgSent);
timer.start();
}
else {
valid.text = "Something went wrong, please try again";
}
}
function msgSent(te:TimerEvent):void {
if(timer.currentCount >= 10) {
init();
timer.removeEventListener(TimerEvent.TIMER, msgSent);
}
}
}
}
}
Keywords:ampersand special characters symbols less-than less than greater-than greater than please don't edit this, it's for others to find this question because you can't search for an '&' and such.
The most obvious culprit here is messy way you're creating the emailData string. As a first step I'd recommend reformatting it to the following:
var urlVars:URLVariables = new URLVariables();
urlVars.name = yourName.htmlText;
urlVars.from = fromEmail.htmlText;
urlVars.subject = yourSubject.htmlText;
urlVars.msg = yourMsg.htmlText;
I think this will automatically URI encode the values, but if not, use encodeURI() as suggested by Mark Knol.
Within Flash, the values need to be encoded, otherwise the querystring could be corrupted.
var emailData:String =
"name=" + encodeURI(yourName.htmlText) +
"&from=" + encodeURI(fromEmail.htmlText) +
"&subject=" + encodeURI(yourSubject.htmlText) +
"&msg=" + encodeURI(yourMsg.htmlText);
Try to use
$emailMsg = utf8_decode($emailMsg);
I decode all my strings I get from Flash.
If this doesn't help, use
$emailMsg = urldecode($emailMsg);
Or both :D
Is there any better way to stop spam coming through on my phpmailer script?
Also how would I go about adding formatting to this so its more readable when it gets sent through to email e.g. break lines
I hope my php syntax is correct - as i do not understand PHP.
<?php
# bool has_injection (String $var, [String $var, ...])
function has_injection () {
$values = func_get_args();
for ($i=0, $count=func_num_args(); $i<$count; $i++) {
if ( stristr($values[$i], "%0A") || stristr($values[$i], "%0D") || stristr($values[$i], "\\r") || stristr($values[$i], "\\n")
|| stristr($values[$i], "Bcc") || stristr($values[$i], "Content-Type") ) {
return true;
}
}
return false;
}
$error = '';
if (isset($_POST) && count($_POST)>0) {
# The form has been submitted
$course_title = $_POST['course_title'];
$course_date = $_POST['course_date'];
$course_code = $_POST['course_code'];
$course_fee = $_POST['course_fee'];
$break .= "\n";
$qual_subject_level = $_POST['qual_subject_level'];
$break .= "\n";
$email = $_POST['email'];
if ($name && $email && $subject) {
if (has_injection($name, $email, $subject)) {
# You've got another spammer at work here
$error = 'No spamming';
exit(0);
}
else {
# It's safe to send the message
mail('my#gmail.com',
$subject,
$course_title,
$course_code,
$course_fee,
$break,
$qual_subject_level,
$break,
$subject,
"From: $name <$email>");
}
}
else {
$error = 'Please fill in all the forms';
}
}
?>
One i use is have a text area and use your .css file to display:none it most bots dont read the css and thus think that the text box is shown and if it has content in it it's a bot if it does not then send your email.
E.G CSS
.antiBot{display:none};
HTML
<input type="text" class="antiBot" name="antibot" value="" />
PHP
<?php
if($_REQUEST['antibot'] == ""){
// send your email
}else{
// bot using your system
}
?>
How ever change the name or bot will get be able to notice its a trap and will get around it with little work insted of having to parse the CSS file for your site
So in your case just rap the if above around your code as for formatting of an email if its plain text use dubble quotes and \n (newline) but it wont work in single quotes.