mail

(PHP 4, PHP 5, PHP 7)

mail메일을 보냅니다

설명

bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

이메일을 보냅니다.

인수

to

메일 수신자.

이 문자열의 형식은 » RFC 2822에 적합해야 합니다. 예를 들면:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

subject

보낼 이메일의 제목.

Caution

제목은 » RFC 2047을 만족해야 합니다.

message

보내질 메세지.

각 줄은 LF(\n)로 구분되어야 합니다. 한 줄은 70 문자를 넘을 수 없습니다.

Caution

(윈도우만) PHP가 SMTP 서버와 직접 통신할 때, 줄 시작의 마침표가 제거됩니다. 이를 방지하려면, 이런 마침표를 2개로 교체할 수 있습니다.

<?php
$text 
str_replace("\n.""\n.."$text);
?>

additional_headers (선택적)

이메일 헤더 마지막에 추가될 문자열.

헤더를 추가하기 위해서 사용됩니다. (From, Cc, Bcc) 여러 추가 헤더는 CRLF(\r\n)로 구분해야 합니다.

Note:

메일을 보낼 때, From 헤더를 포함해야 합니다. 이는 additional_headers 인수를 통하여 설정하거나, 기본값을 php.ini에 설정할 수 있습니다.

이 작업을 하지 않으면 다음과 비슷한 오류 메세지가 출력됩니다. Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. 윈도우에서 From 헤더는 Return-Path도 설정합니다.

Note:

메세지가 전달되지 않으면, LF(\n)만 사용해 보십시오. 몇몇 질 나쁜 유닉스 메일 전송 에이전트는 자동으로 LF를 CRLF로 교체합니다. (이 경우 CRLF를 쓰면 CR이 두번 들어가게 됩니다) 이는 최후 수단이여야 하며, » RFC 2822에 적합하지 않습니다.

additional_parameters

sendmail_path 설정을 사용하여 메을을 보낼 때, additional_parameters 인수를 사용하여 추가적인 인수를 전달할 수 있습니다. 예를 들면, -f sendmail 옵션을 사용하여 봉투 전송 주소를 넣을 수 있습니다.

웹 서버를 운영하는 사용자는 sendmail 설정에 신뢰하는 사용자를 추가하여, 이 방식(-f)으로 봉투 전송 주소를 넣을 때 'X-Warning' 헤더 추가를 막을 수 있습니다. sendmail 사용자라면, 이 파일은 /etc/mail/trusted-users입니다.

반환값

메일이 성공적으로 전송이 허용되었을 때는 TRUE, 그 외에는 FALSE를 반환합니다.

이는 메일 전송이 허용 되었을 뿐, 원하는 목적지에 도착한 것을 의미하는 것이 아니라는 점에 주의하십시오.

변경점

버전 설명
4.3.0 (윈도우만) 모든 사용자 헤더(From, Cc, Bcc, Date 등)를 지원하고, 대소문자를 구분하지 않습니다. (사용자 헤더를 직접 MTA에 보내지 않고 먼저 PHP에서 처리함으로써, PHP < 4.3만 Cc 헤더 요소를 지원하고, 대소문자 구분을 하지 않습니다)
4.2.3 safe_mode에서 additional_parameters 인수를 쓸 수 없고, mail() 함수를 이 인수와 함께 사용하면 경고 문구를 출력하고 FALSE를 반환합니다.
4.0.5 additional_parameters 인수가 추가되었습니다.

예제

Example #1 메일 보내기.

간단한 이메일을 보내기 위해 mail() 사용하기:

<?php
// 메세지
$message "Line 1\nLine 2\nLine 3";

// 한 줄이 70 문자를 넘어갈 때를 위하여, wordwrap()을 사용해야 합니다.
$message wordwrap($message70);

// 전송
mail('caffeinated@example.com''My Subject'$message);
?>

Example #2 추가 헤더와 함께 메일 보내기

기본 헤더를 추가하여, MUA에게 From과 Reply-To 주소를 알려줍니다:

<?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);
?>

Example #3 추가적인 명령줄 인수와 함께 메일 전송하기.

additional_parameters 인수는 메일을 보낼 때 사용하는 sendmail_path 설정에 있는 프로그램에 추가 인수를 넘깁니다.

<?php
mail
('nobody@example.com''the subject''the message'null,
   
'-fwebmaster@example.com');
?>

Example #4 HTML 이메일 보내기

mail()로 HTML 이메일을 보낼 수 있습니다.

<?php
/* 다중 수신자 */
$to  'aidan@example.com' ', ' // 콤마인 것에 주의.
$to .= 'wez@example.com';

// 제목
$subject 'Birthday Reminders for August';

// 메세지
$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>
'
;

// HTML 메일을 보내려면, Content-type 헤더를 설정해야 합니다.
$headers  'MIME-Version: 1.0' "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' "\r\n";

// 추가 헤더
$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($to$subject$message$headers);
?>

Note:

HTML이나 다른 복잡한 메일을 보낼 때는, PEAR 패키지 » PEAR::Mail_Mime 사용을 권장합니다.

주의

Note:

윈도우에서 mail()은 유닉스에서와는 많은 점이 다릅니다. 첫번째로, 메세지 작성에 로컬 바이너리를 사용하지 않고 직접 소켓으로 작동합니다. 즉, MTA 네트워크 소켓(로컬호스트건 원격이건)이 열려 있어야 합니다.

두번째로, From:, Cc:, Bcc:, Date: 등의 사용자 헤더는 MTA에 직접 해석되지 않으며, PHP에서 처리합니다.

그러므로, to 인수는 "Something <someone@example.com>" 형태로 주어져서는 안됩니다. mail 명령은 MTA와 통신할 때 이를 정상적으로 처리하지 못할 수 있습니다.

Note:

첨부 파일과 특수한 내용 형식(예, HTML)을 가진 이메일을 이 함수로 보낼 수 있습니다. 이는 MIME-인코딩으로 이루어 집니다 - 자세한 사항은 » 젠드 글이나 » PEAR Mime 클래스를 참조하십시오.

Note:

mail() 함수는 루프를 돌며 많은 양의 이메일을 처리하기엔 적합하지 않습니다. 이 함수는 각 이메일에 대하여 SMTP 소켓을 열고 닫으며, 매우 비효율적입니다.

많은 양의 이메일을 보내려면, » PEAR::Mail» PEAR::Mail_Queue 패키지를 알아보십시오.

Note:

다음 RFC가 유용합니다: » RFC 1896, » RFC 2045, » RFC 2046, » RFC 2047, » RFC 2048, » RFC 2049, » RFC 2822.

참고

add a note add a note

User Contributed Notes 20 notes

up
32
Anonymous
7 years ago
Security advice: Although it is not documented, for the parameters $to and $subject the mail() function changes at least \r and \n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

The crucial part is the $additional_headers parameter. This parameter can't be cleaned by the mail() function. So it is up to you to prevent unwanted \r or \n to be inserted into the values you put in there. Otherwise you just created a potential spam distributor.
up
26
php at simoneast dot net
7 years ago
Often it's helpful to find the exact error message that is triggered by the mail() function. While the function doesn't provide an error directly, you can use error_get_last() when mail() returns false.

<?php
$success
= mail('example@example.com', 'My Subject', $message);
if (!
$success) {
   
$errorMessage = error_get_last()['message'];
}
?>

(Tested successfully on Windows which uses SMTP by default, but sendmail on Linux/OSX may not provide the same level of detail.)

Thanks to https://stackoverflow.com/a/20203870/195835
up
4
priyanshkala3 at gmail dot com
11 months ago
Sending mail using XAMPP server

I encountered numerous issues while attempting to send emails using the XAMPP server. However, I eventually found the correct method to accomplish it.

Configuring PHP's mail functionality to work with Gmail's SMTP server involves editing the `php.ini` and `sendmail.ini` configuration files. Below are the formal steps for setting up PHP to send emails through Gmail's SMTP server using XAMPP:

Configuring php.ini:

1. Open `php.ini` in an editor:
   Open the `php.ini` configuration file in your preferred text editor.

2. Locate the mail function:
   Use the search function (Ctrl + F) to find the section related to the mail function within the `php.ini` file.

3. Update mail function settings:
   Copy and paste the following configuration parameters into the mail function section. Comment out or disable all other settings related to mail.

   php.ini code to be edited:

   SMTP=smtp.gmail.com
   smtp_port=587
   sendmail_from = yourmail@gmail.com
   sendmail_path = write_sendmail.exe_path
  

4. Save the changes:
   Save the `php.ini` file after applying the modifications.

Configuring sendmail.ini (in XAMPP folder):

1. Open `sendmail.ini` in XAMPP folder:
   Locate and open the `sendmail.ini` configuration file within the XAMPP directory.

2. Adjust SMTP settings:
   Insert the following content into the `sendmail.ini` file, marking other configurations as comments:

   sendmail.ini code :

   smtp_server=smtp.gmail.com
   smtp_port=587
   error_logfile=error.log
   debug_logfile=debug.log
   auth_username=yourmail@gmail.com
auth_password=app_password_after_enabling_two_factor_authentication_for_your_mail_id
   force_sender=priyansh.kala.4@gmail.com
  

3. Save the changes:
   Save the `sendmail.ini` file after inserting the specified configurations.

These steps configure PHP to utilize Gmail's SMTP server for sending emails. Ensure that the modifications are saved and that the necessary XAMPP services are restarted for the changes to take effect.

Please note that using hardcoded passwords in configuration files poses a security risk. Storing passwords directly in plain text files should be avoided in production environments. Consider using environment variables or secure credential management systems for better security practices.

Code for sending mail-:

<?php
$subject
= "Mail for checking";
$msg = "Hey! Let us play with PHP.";
$receiver = "reciever@gmail.com";
mail($receiver, $subject, $msg);
?>
up
21
Anonymous
5 years ago
If you notice wrong displayed characters in the email it's because you need to properly set the Content-Type and the Charset in the headers of the email:

<?php
$headers
= 'Content-Type: text/plain; charset=utf-8' . "\r\n";
?>

Mostly, UTF-8 is your best choice.

You can set custom headers with the fourth parameter of the mail() function.

To make the whole thing waterproof, add the following header too:

<?php
$headers
.= 'Content-Transfer-Encoding: base64' . "\r\n";
?>

Now you can use the combination of UTF-8 and Base64 to properly encode the subject line and the recipient name like this:

<?php
$subject
= '=?UTF-8?B?' . base64_encode('Test email with German Umlauts öäüß') . '?=';
$recipient = '=?UTF-8?B?' . base64_encode('Margret Müller') . '?= <recipient@domain.com>';
?>

And don't forget to Base64 encode the email message too:

<?php
$message
= base64_encode('This email contains German Umlauts öäüß.');
?>

All references are taken from:
https://dev.to/lutvit/how-to-make-the-php-mail-function-awesome-3cii
up
7
pangz dot lab at gmail dot com
4 years ago
* Sending email with attachment

function sendMail(
    string $fileAttachment,
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    string $toAddress   = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {
   
    $fileAttachment = trim($fileAttachment);
    $from           = $fromMail;
    $pathInfo       = pathinfo($fileAttachment);
    $attchmentName  = "attachment_".date("YmdHms").(
    (isset($pathInfo['extension']))? ".".$pathInfo['extension'] : ""
    );
   
    $attachment    = chunk_split(base64_encode(file_get_contents($fileAttachment)));
    $boundary      = "PHP-mixed-".md5(time());
    $boundWithPre  = "\n--".$boundary;
   
    $headers   = "From: $from";
    $headers  .= "\nReply-To: $from";
    $headers  .= "\nContent-Type: multipart/mixed; boundary=\"".$boundary."\"";
   
    $message   = $boundWithPre;
    $message  .= "\n Content-Type: text/plain; charset=UTF-8\n";
    $message  .= "\n $mailMessage";
   
    $message .= $boundWithPre;
    $message .= "\nContent-Type: application/octet-stream; name=\"".$attchmentName."\"";
    $message .= "\nContent-Transfer-Encoding: base64\n";
    $message .= "\nContent-Disposition: attachment\n";
    $message .= $attachment;
    $message .= $boundWithPre."--";
   
    return mail($toAddress, $subject, $message, $headers);
}

* Sending email in html

function sendHtmlMail(
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    array $toAddress    = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {
   
    $to        = implode(",", $toAddress);
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=iso-8859-1';   
    $headers[] = 'To: '.$to;
    $headers[] = 'From: '.$fromMail;   

    return mail($to, $subject, $mailMessage, implode("\r\n", $headers));
}
up
6
Mark Simon
5 years ago
It is worth noting that you can set up a fake sendmail program using the sendmail_path directive in php.ini.

Despite the comment in that file, sendmail_path also works for Window. From https://www.php.net/manual/en/mail.configuration.php#ini.sendmail-path:

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.
up
9
charles dot fisher at arconic dot com
7 years ago
I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
$smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

$B = 8192;
$c = "\r\n";
$s = 'myapp@someserver.com';

fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
  $junk = fgets($smtp, $B);

// Envelope
fwrite($smtp, 'mail from: ' . $s . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
  $junk = fgets($smtp, $B);

// Header
fwrite($smtp, 'To: ' . $to . $c);
if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
if(strlen($headers)) fwrite($smtp, $headers); // Must be \r\n (delimited)
fwrite($smtp, $headers . $c);

// Body
if(strlen($body)) fwrite($smtp, $body . $c);
fwrite($smtp, $c . '.' . $c);
  $junk = fgets($smtp, $B);

// Close
fwrite($smtp, 'quit' . $c);
  $junk = fgets($smtp, $B);
fclose($smtp);
}
up
2
imme_emosol
1 year ago
Also see chunk_split (as "alternative" to wordwrap).
up
7
chris at ocproducts dot com
7 years ago
The 'sendmail' executable which PHP uses on Linux/Mac (not Windows) expects "\n" as a line separator.

This executable is a standard, and emulated by other MTAs.

"\n" is confirmed required for qmail and postfix, probably also for sendmail and exim but I have not tested.

If you pass through using "\r\n" as a separator it may appear to work, but your email will be subtly corrupted and some middleware may break. It only works because some systems will clean up your mistake.

If you are implementing DKIM be very careful, as DKIM checks will fail (at least on popular validation tools) if you screw this up. DKIM must be calculated using "\r\n" but then you must switch it all to "\n" when using the PHP mail function.

On Windows, however, you should use "\r\n" because PHP is using SMTP in this situation, and hence the normal rules of the SMTP protocol (not the normal rules of Unix piping) apply.
up
10
Porjo
14 years ago
Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code
up
5
eeeugeneee
7 years ago
Send mail with minimal requirements from email services.

<?php
    $encoding
= "utf-8";

   
// Preferences for Subject field
   
$subject_preferences = array(
       
"input-charset" => $encoding,
       
"output-charset" => $encoding,
       
"line-length" => 76,
       
"line-break-chars" => "\r\n"
   
);

   
// Mail header
   
$header = "Content-type: text/html; charset=".$encoding." \r\n";
   
$header .= "From: ".$from_name." <".$from_mail."> \r\n";
   
$header .= "MIME-Version: 1.0 \r\n";
   
$header .= "Content-Transfer-Encoding: 8bit \r\n";
   
$header .= "Date: ".date("r (T)")." \r\n";
   
$header .= iconv_mime_encode("Subject", $mail_subject, $subject_preferences);

   
// Send mail
   
mail($mail_to, $mail_subject, $mail_message, $header);
?>
up
0
atesin > gmail
1 year ago
mail() internals:

doing some tests i can say... if sendmail_path is defined in php.ini or by ini.set(), by calling function like...

mail($to, $subject, $message, $headers, $params)

would be like if php open a shell internally, execute this command, send this text to stdin, and return true if return value == 0

------------
shell> $sendmail_path $params
To: $to
Subject: $subject
$headers

$message
(EOF)
------------

in windows instead using php smtp which is very limited, i prefer to force use sendmail-like behavior, by setting sendmail_path and then use msmtp for windows
up
2
pavel.lint at vk.com
12 years ago
Here's a small handy function I use to send email in UTF-8.

<?php
function mail_utf8($to, $from_user, $from_email,
                                            
$subject = '(No subject)', $message = '')
   {
     
$from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
     
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";

     
$headers = "From: $from_user <$from_email>\r\n".
              
"MIME-Version: 1.0" . "\r\n" .
              
"Content-type: text/html; charset=UTF-8" . "\r\n";

     return
mail($to, $subject, $message, $headers);
   }
?>
up
0
ABOMB
12 years ago
I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...
up
0
Ben Cooke
18 years ago
Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.
up
-3
rexlorenzo at gmail dot com
12 years ago
Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from \r\n Bcc: $bcc \r\n";

But this did:

$headers = "From: $from\r\nBcc: $bcc\r\n";

Notice the removal of the spaces around the first \r\n.
up
-2
Anonymous
1 year ago
So far I used the following to make sure special charakters where correctly shown in the mail subject:

<?php $subject = '=?utf-8?B?' . base64_encode($subject) . '?='; ?>

But with very long subjects, the header line gets longer than 76 chars and some e-mail servers really don't like that... So this is my new solution:

<?php $subject = substr(mb_encode_mimeheader("Subject: " . $subject, 'utf-8', 'B', "\r\n", 0), 9); ?>

Please note: I added "Subject: " in front of $subject and stripped it of afterwards. This is to make sure, that the necessarry space is reserved, as PHP will add the "Subject: " itself...
up
-3
andrew at my-syte dot com
2 years ago
Regarding To:

be careful not to duplicate To in the additional_headers,

lest gmail already flags it thus:

host gmail-smtp-in.l.google.com [142.251.xx.xx]
SMTP error from remote mail server after end of data:
550-5.7.1 [xxx.xxx.xx.xx] This message is not RFC 5322 compliant, the issue is:
550-5.7.1 duplicate To headers. To reduce the amount of spam sent to Gmail,
550-5.7.1 this message has been blocked. Please review
550 5.7.1 RFC 5322 specifications for more information.
up
-16
Max AT
12 years ago
To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers
= "MIME-Version: 1.0\n" ;
       
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";

       
$headers .= "Sensitivity: Personal\n";

$status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.
up
-37
php dot net at schrecktech dot com
19 years ago
When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...
To Top