동일한 스크립트로 제출시 HTML 양식에서 PHP로 이메일 보내기
사용자가 HTML 양식 작성을 마친 후 양식에서 정보를 이메일로 보내면 PHP로 이메일을 보내고 싶습니다. 양식이있는 웹 페이지를 표시하는 동일한 스크립트에서 수행하고 싶습니다.
이 코드를 찾았지만 메일이 전송되지 않습니다.
<?php
if (isset($_POST['submit'])) {
$to = $_POST['email'];
$subject = $_POST['name'];
$message = getRequestURI();
$from = "zenphoto@example.com";
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)) {
echo "Mail Sent.";
}
else {
echo "failed";
}
}
?>
PHP로 이메일을 보내는 코드는 무엇입니까?
편집 (# 1)
내가 올바르게 이해했다면 모든 것을 한 페이지에 넣고 동일한 페이지에서 실행하기를 원합니다.
당신은 예를 들어, 하나의 페이지에서 메일을 보낼 때 다음과 같은 코드를 사용할 수 있습니다 index.php
또는contact.php
이 답변과 내 원래 답변의 유일한 차이점 <form action="" method="post">
은 작업이 비어있는 곳입니다.
나중에 사용자를 다른 페이지로 리디렉션하려면 PHP 처리기 header('Location: thank_you.php');
대신 사용 하는 것이 좋습니다 echo
.
아래의 전체 코드를 하나의 파일로 복사하십시오.
<?php
if(isset($_POST['submit'])){
$to = "email@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
원래 답변
질문이 무엇인지 잘 모르겠지만 양식을 작성한 사람에게 메시지의 사본을 보내야한다는 인상을 받았습니다.
다음은 HTML 양식 및 PHP 처리기의 테스트 / 작업 복사본입니다. 이것은 PHP mail()
기능을 사용합니다 .
PHP 핸들러는 양식을 작성한 사람에게도 메시지 사본을 보냅니다.
사용 //
하지 않을 경우 코드 줄 앞에 두 개의 슬래시 를 사용할 수 있습니다.
예 : // $subject2 = "Copy of your form submission";
실행되지 않습니다.
HTML 양식 :
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP 핸들러 (mail_handler.php)
(HTML 양식의 정보를 사용하고 이메일을 보냅니다.)
<?php
if(isset($_POST['submit'])){
$to = "email@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>
HTML로 보내려면 :
HTML과 두 인스턴스 모두에 대해 메일을 보내려면 서로 다른 변수 이름을 가진 두 개의 별도 HTML 헤더 세트를 만들어야합니다.
mail()
이메일을 HTML로 보내는 방법을 알아 보려면 설명서를 읽으십시오 .
각주 :
- HTML5와 관련하여
action 속성을 사용하여 제출 된 데이터를 처리 할 서비스의 URL을 지정해야합니다.
https://www.w3.org/TR/html5/forms.html 에 설명 된대로 4.10.1.3 서버와 통신하도록 양식 구성 . 전체 정보는 페이지를 참조하십시오.
따라서 action=""
HTML5에서는 작동하지 않습니다.
적절한 구문은 다음과 같습니다.
action="handler.xxx"
또는action="http://www.example.com/handler.xxx"
.
참고 xxx
파일 형식의 확장이 될 것입니다 프로세스를 처리하는 데 사용. 이것은 수 .php
, .cgi
, .pl
, .jsp
파일 확장자 등
메일 전송에 실패하면 Stack에 대한 다음 Q & A를 참조하세요.
PHP script to connect to a SMTP server and send email on Windows 7
Sending an email from PHP in Windows is a bit of a minefield with gotchas and head scratching. I'll try to walk you through one instance where I got it to work on Windows 7 and PHP 5.2.3 under (IIS) Internet Information Services webserver.
I'm assuming you don't want to use any pre-built framework like CodeIgniter or Symfony which contains email sending capability. We'll be sending an email from a standalone PHP file. I acquired this code from under the codeigniter hood (under system/libraries) and modified it so you can just drop in this Email.php file and it should just work.
This should work with newer versions of PHP. But you never know.
Step 1, You need a username/password with an SMTP server:
I'm using the smtp server from smtp.ihostexchange.net
which is already created and setup for me. If you don't have this you can't proceed. You should be able to use an email client like thunderbird, evolution, Microsoft Outlook, to specify your smtp server and then be able to send emails through there.
Step 2, Create your Hello World Email file:
I'm assuming you are using IIS. So create a file called index.php under C:\inetpub\wwwroot
and put this code in there:
<?php
include("Email.php");
$c = new CI_Email();
$c->from("FromUserName@foobar.com");
$c->to("user_to_receive_email@gmail.com");
$c->subject("Celestial Temple");
$c->message("Dominion reinforcements on the way.");
$c->send();
echo "done";
?>
You should be able to visit this index.php by navigating to localhost/index.php in a browser, it will spew errors because Email.php is missing. But make sure you can at least run it from the browser.
Step 3, Create a file called Email.php
:
Create a new file called Email.php under C:\inetpub\wwwroot
.
Copy/paste this PHP code into Email.php:
https://github.com/sentientmachine/standalone_php_script_send_email/blob/master/Email.php
Since there are many kinds of smtp servers, you will have to manually fiddle with the settings at the top of Email.php
. I've set it up so it automatically works with smtp.ihostexchange.net
, but your smtp server might be different.
For example:
- Set the smtp_port setting to the port of your smtp server.
- Set the smtp_crypto setting to what your smtp server needs.
- Set the $newline and $crlf so it's compatible with what your smtp server uses. If you pick wrong, the smtp server may ignore your request without error. I use \r\n, for you maybe
\n
is required.
The linked code is too long to paste as a stackoverflow answer, If you want to edit it, leave a comment in here or through github and I'll change it.
Step 4, make sure your php.ini has ssl extension enabled:
Find your PHP.ini file and uncomment the
;extension=php_openssl.dll
So it looks like:
extension=php_openssl.dll
Step 5, Run the index.php file you just made in a browser:
You should get the following output:
220 smtp.ihostexchange.net Microsoft ESMTP MAIL Service ready at
Wed, 16 Apr 2014 15:43:58 -0400 250 2.6.0
<534edd7c92761@summitbroadband.com> Queued mail for delivery
lang:email_sent
done
Step 6, check your email, and spam folder:
Visit the email account for user_to_receive_email@gmail.com and you should have received an email. It should arrive within 5 or 10 seconds. If you does not, inspect the errors returned on the page. If that doesn't work, try mashing your face on the keyboard on google while chanting: "working at the grocery store isn't so bad."
If you haven't already, look at your php.ini
and make sure the parameters under the [mail function]
setting are set correctly to activate the email service. After you can use PHPMailer library and follow the instructions.
You can also use mandrill app to send the mail in php. You will get the API from https://mandrillapp.com/api/docs/index.php.html where you can find the complete details about emails sended and other details.
You need to add an action
into your form like:
<form name='form1' method='post' action='<?php echo($_SERVER['PHP_SELF']);'>
<!-- All your input for the form here -->
</form>
Then put your snippet in the top of the document en send the mail. What echo($_SERVER['PHP_SELF']);
does is that it sends your information the top of your script so you could use it.
Here are the PHP mail settings I use:
//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "zenphoto@example.com";
//data
$msg = "Your MSG <br>\n";
//Headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;
mail($to,$subject,$msg,$headers);
echo "Mail Sent.";
You need a SMPT Server in order for
... mail($to,$subject,$message,$headers);
to work.
You could try light weight SMTP servers like xmailer
I think one error in the original code might have been that it had:
$message = echo getRequestURI();
instead of:
$message = getRequestURI();
(The code has since been edited though.)
'code' 카테고리의 다른 글
android의 webview에서 onclick 이벤트를 어떻게 얻을 수 있습니까? (0) | 2020.11.17 |
---|---|
JAX-RS의 필수 @QueryParam (및 부재시 수행 할 작업) (0) | 2020.11.17 |
Map [string] int를 값으로 정렬하는 방법은 무엇입니까? (0) | 2020.11.17 |
독일어 키보드의 줄 주석 단축키 (0) | 2020.11.17 |
API 23의 Android 권한 일반 권한 및 위험한 권한 목록? (0) | 2020.11.17 |