>  기사  >  백엔드 개발  >  PHP 메일()

PHP 메일()

WBOY
WBOY원래의
2024-08-29 13:08:50345검색

mail() 기능을 사용하면 스크립트에서 직접 메일을 쉽게 보낼 수 있습니다. 일반적으로 5개의 매개변수를 허용하지만 그 중 처음 3개만 필수이고 나머지 두 매개변수는 선택사항이며 모든 매개변수가 mail() 함수의 괄호 안에 언급된 경우 필수가 아닙니다. 필요할 때마다 어떤 형식이나 다른 형식을 사용하여 웹사이트나 블로그에서 직접 메일을 보내는 데 도움이 됩니다. 이는 PHP 스크립트 또는 스크립트에서 일부 이메일을 보내는 데 도움이 되는 PHP 프로그래밍 언어의 내장 기능입니다. 중요한 작업이나 이벤트를 사용자에게 알릴 때 비용 효율적입니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문 및 매개변수

다음은 구문입니다

mail(to1, subject1, message1, headers1, parameters1);

mail() 함수 매개변수 설명:

  • mail() 함수의 to1 매개변수: PHP 프로그래밍 언어의 mail() 함수의 "to1" 매개변수는 필수 필드입니다. 메일 수신자/수신자를 지정하는 데 도움이 됩니다.
  • mail() 함수의 subject1 매개변수: PHP 프로그래밍 언어의 mail() 함수의 "subject1" 매개변수도 필수 필드입니다. 이메일 제목을 지정하는 데 도움이 됩니다. 이 매개변수에는 모든 유형의 개행 문자가 포함될 수도 있고 포함되지 않을 수도 있습니다.
  • mail() 함수의 message1 매개변수: PHP 프로그래밍 언어의 mail() 함수의 “message1” 매개변수도 위의 2개 매개변수와 마찬가지로 필수 필드입니다. 전송될 메시지를 정의하는 데 도움이 됩니다. 각 줄은 LF(n)로 구분되어야 합니다. 각 줄은 70자를 초과할 수 없습니다. Windows에서는 메시지의 특정 줄 시작 부분에 FULLSTOP이 있으면 제거될 수 있습니다. 이런 유형의 문제를 해결하려면 FULL STOP 문자를 이중 점 문자 “..”의 도움으로 바꿔야 합니다.
  • mail() 함수의 headers1 매개변수: PHP 언어의 headers1 매개변수는 선택 필드이지만 Cc, From, Bcc 함수와 같은 일부 추가 헤더를 지정하는 데 도움이 됩니다. 추가 헤더 중 일부는 CRLF – (rn)로 구분됩니다. 이메일을 보내는 과정에서 일부 From 헤더가 포함될 수 있습니다. 이는 headers1 매개변수 또는 PHP.INI 형식 파일을 사용하여 설정할 수 있습니다.
  • mail() 함수의 parameters1 매개변수: 메일 함수의parameters1 매개변수는 선택사항입니다. 이 매개변수는 추가 매개변수를 지정합니다. 이메일 전송 프로그램에 추가 매개변수를 지정하는 데 도움이 됩니다. -f 메일 보내기 옵션을 사용하면 봉투 보낸 사람 주소로 설정됩니다.

PHP에서 mail() 함수는 어떻게 작동하나요?

PHP 프로그래밍 언어의 mail() 기능은 PHP 스크립트 자체에서 직접 메일을 보내는 데 도움을 주는 역할을 합니다. PHP 4+ 버전에서 작동합니다. PHP 4 버전 이전에는 이 mail()이 작동하지 않으므로 PHP 버전이 PHP 4 버전보다 이전인 경우 mail() 기능을 사용하지 마십시오. 주소 매개변수의 해시 값을 반환하여 작동합니다. 하지만 메일이 배송 승인을 받았다고 해서 실제로 이메일이 수신되거나 전송되는 것은 아니라는 점을 명심해야 합니다.

PHP 4.0.5 버전에는 매개변수 1이 추가되었습니다. PHP 4.2.3 PHP 버전에서는 안전 모드에서 매개변수 1이 비활성화되어 있습니다. Windows O.S의 PHP 4.3.0 버전에서. 참조, 숨은 참조, 보낸 사람, 날짜와 같은 일부 사용자 정의 헤더를 허용하며 대소문자를 구분하지 않습니다. PHP 5.4 버전에서는 헤더 매개변수 목적으로만 헤더 삽입 방지가 추가되었습니다. PHP 7.2 버전에서는 headers1 매개변수도 배열을 허용합니다.

다음은 언급된 예시입니다.

예시 #1

이 예에서는 PHP 프로그래밍 언어의 mail() 함수를 구현해 보겠습니다. 여기서 처음에는 PHP 태그가 생성되고 그 안에 일부 변수가 일부 값과 함께 생성됩니다. 처음에 "to_email1"은 메일을 보내는 데 필요한 특정 이메일/Gmail 주소인 문자열 값으로 생성됩니다. 그런 다음 "subject1" 변수가 제목으로 표시할 일부 문자열 콘텐츠로 생성되고 메시지 변수가 생성된 다음 중요한 메시지 텍스트 정보/기타가 할당됩니다. to_email1 주소의 사람에게 정보를 지정하는 것입니다. 그런 다음 header1 변수가 생성됩니다. 그런 다음 주요 PHP 함수인 mail()이 사용됩니다. 여기에서는 mail() 함수 내부에 4개의 매개변수가 포함되어 있습니다. 이 기능은 PHP 스크립트 자체로 메일을 보내는 데 도움이 됩니다.

코드:

<?php
$to_email1 = 'name1 @ company .com';
$subject1 = 'Testing the PHP Mail';
$message1 = 'This mail is sent using the PHP mail function';
$headers1 = 'From: noreply @ company .com';
mail($to_email1,$subject1,$message1,$headers1);
?>

출력:

PHP 메일()

Example #2

This is the example of implementing the custom functions which helps in sending the secure mail to a specific person only with the help of the mail() function inside the PHP script. Here at first a function with some fields are created along with the condition statements. Then “to_email1” variable is created with some email address. Then subject1, messages, and headers1 variables are created. Based on the IF ELSE conditions and the mail() function along with the HTML display elements the program will run and the mail will be sent to the specified email person or other but the PHP.INI file settings should be perfect or use any online compiler if possible.

Code:

<?php
functionsanitize_my_email($field1) {
$field1 = filter_var($field1, FILTER_SANITIZE_EMAIL);
if (filter_var($field1, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email1 = 'name @ company .com';
$subject1 = 'Testing PHP Mail';
$message1 = 'This mail is sent using the PHP mail ';
$headers1 = 'From: noreply @ company. com';
//check whether the email address is invalid or not $secure_check
$secure_check1 = sanitize_my_email($to_email1);
if ($secure_check1 == false) {
echo "Invalid input";
} else { //send email
mail($to_email1, $subject1, $message1, $headers1);
echo "This email is now sent using the PHP Mail";
}
?>

Output:

PHP 메일()

Example #3

This is the example of implementing the PHP mail() function without using the header1 parameter inside of the mail() function of the PHP Programming Language. It is a simple mail but the header1 parameter is not used.

Code:

<?php
$to1 = '[email&#160;protected]';
$subject1 = 'The Marriage Proposal';
$message1 = 'Hi Radha, will you marry me? Say Yes or No';
$from1 = '[email&#160;protected]';
// Sending email
if(mail($to1, $subject1, $message1)){
echo 'Now Your mail will be sent automatically and successfully.';
} else{
echo 'Now it is Unable to send the email/gmail. Please try again.';
}
?>

Output:

PHP 메일()

Example #4

This is the example of implementing the PHP mail() function in order to send an attachment file along with the mail. Here at first HTML form is created for some variable values and to get the attachment file. After clicking the submit button the PHP mail() function works with the help of the PHP mail function code. Then the output text will be displayed as shown in the output section below.

HTML File Code:

<html>
<body>
<form enctype="multipart/form-data" method="POST" action="string22.php">
<label>Your Name1 <input type="text" name="sender_name1" /></label><br>
<label>Your Email1 <input type="email" name="sender_email1" /></label><br>
<label>Subject1 <input type="text" name="subject1" /></label><br>
<label>Message1 <textarea name="message1"></textarea></label><br>
<label>Attachment1 <input type="file" name="attachment1" /></label><br>
<label><input type="submit" name="button" value="Submit" /></label><br>
</form>
</body>
</html>

PHP File Code:

<?php
if($_POST['button'] &&isset($_FILES['attachment1']))
{
$from_email         = '[email&#160;protected]'; //from mail, sender email addrress
$recipient_email    = '[email&#160;protected]'; //recipient email addrress
//Load POST data from HTML form
$sender_name1    = $_POST["sender_name1"] //sender name1
$reply_to_email = $_POST["sender_email1"] //sender email1, it will be used in "reply-to" header
$subject1        = $_POST["subject1"] //subject1 for the email
$message1        = $_POST["message1"] //message1 body1 of the email
//Get uploaded file data using $_FILES array
$tmp_name    = $_FILES['my_file']['tmp_name']; // Now get the temporary file name1 of the file on the server
$name        = $_FILES['my_file']['name'];  // Now get the name of the file1
$size        = $_FILES['my_file']['size'];  // Now get size of the file1 for size validation
$type        = $_FILES['my_file']['type'];  // Now get type of the file1
$error       = $_FILES['my_file']['error']; // Now get the error (if any)
//It is a validating form field which helps in attaching the file
if($file_error> 0)
{
die('Upload error or No files uploaded');
}
//It is like reading from a specific uploaded file and also the base64_encode content1
$handle1 = fopen($tmp_name, "r");  // Now setting the file handle1 only for reading the file
$content1 = fread($handle1, $size); // Now reading the file
fclose($handle1);                  // Now close upon completion
$encoded_content11 = chunk_split(base64_encode($content1));
$boundary1 = md5("random"); // Now defining the boundary1 with a md5 hashed value
//Now header
$headers1 = "MIME-Version: 1.0\r\n"; // Now Defining the MIME version
$headers1 .= "From:".$from_email."\r\n"; // Now the Sender Email
$headers1 .= "Reply-To: ".$reply_to_email."\r\n"; // Now Email addrress to reach back
$headers1 .= "content1-Type: multipart/mixed;\r\n"; // Now Defining content1-Type
$headers1 .= "boundary1 = $boundary1\r\n"; // Now Defining the boundary1
//Now this is about plain text
$body1 = "--$boundary1\r\n";
$body1 .= "content1-Type: text/plain; charset=ISO-8859-1\r\n";
$body1 .= "content1-Transfer-Encoding: base64\r\n\r\n";
$body1 .=chunk_split(base64_encode($message1));
//NOw attachment1
$body1 .= "--$boundary1\r\n";
$body1 .="content1-Type: $file_type; name=".$file_name."\r\n";
$body1 .="content1-Disposition: attachment1; filename=".$file_name."\r\n";
$body1 .="content1-Transfer-Encoding: base64\r\n";
$body1 .="X-attachment1-Id: ".rand(1000, 99999)."\r\n\r\n";
$body1 .= $encoded_content11; // NOw Attaching the encoded file with email
$sentMailResult1 = mail($recipient_email, $subject1, $body1, $headers1);
if($sentMailResult1 )
{
echo "This mail is sent using the PHP mail function"; // Now it will be printed only if the file is going to be sent successfully
unlink($name); // Now deleting the file just after the attachment1 is sent.
}
else
{
die("Sorry attachment mail not sent");
}
}
?>

Output of HTML Code:

PHP 메일()

Output of PHP Code:

PHP 메일()

Conclusion

We hope you learned what is the definition of PHP mail() function along with its syntax and explanation of the parameter of the mail() function, How the mail() function works in PHP along with various examples to under mail() concept better and so easily.

위 내용은 PHP 메일()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.