PHP मेल () के साथ अटैचमेंट भेजें?


224

मुझे मेल के साथ एक पीडीएफ भेजने की आवश्यकता है, क्या यह संभव है?

$to = "xxx";
$subject = "Subject" ;
$message = 'Example message with <b>html</b>';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: xxx <xxx>' . "\r\n";
mail($to,$subject,$message,$headers);

मैं क्या खो रहा हूँ?

php 

16
mail()फ़ंक्शन के साथ अनुलग्नक भेजने के लिए आपकी अपेक्षा से अधिक कठिन है, अपने समय के लिए, PHPMailer
Mihai Iorga

1
या आप इसे लिंक कर सकते हैं?

@mihai lorga सर्वर साइड इंस्टॉल की आवश्यकता नहीं है? यदि यह बिना किसी एक्सटेंशन या प्लगइन्स के रहने योग्य है, तो मुझे यह जानना होगा कि कैसे।


2
@ChristianNikkanen यह सिर्फ एक अच्छी तरह से सेट की गई स्क्रिप्ट है, इसमें बहुत सारी विशेषताएं हैं जिन्हें पूरा करना कठिन है। पहिया को क्यों मजबूत करना है? यह किसी भी अतिरिक्त प्लगइन्स का उपयोग नहीं करता है।
Mihai Iorga

जवाबों:


310

मैं टिप्पणियों में @MihaiIorga से सहमत हूं - PHPMailer स्क्रिप्ट का उपयोग करें। आपको लगता है कि आप इसे अस्वीकार कर रहे हैं क्योंकि आप आसान विकल्प चाहते हैं। मुझ पर विश्वास करो, PHPMailer है एक बहुत बड़े अंतर से आसान विकल्प यह अपने आप PHP के अंतर्निहित के साथ क्या करने की कोशिश कर की तुलना में mail()कार्य करते हैं। PHP का mail()कार्य वास्तव में बहुत अच्छा नहीं है।

PHPMailer का उपयोग करने के लिए:

  • यहां से PHPMailer स्क्रिप्ट डाउनलोड करें: http://github.com/PHPMailer/PHPMailer
  • संग्रह को निकालें और स्क्रिप्ट के फ़ोल्डर को अपनी परियोजना में सुविधाजनक स्थान पर कॉपी करें।
  • मुख्य स्क्रिप्ट फ़ाइल शामिल करें - require_once('path/to/file/class.phpmailer.php');

अब, अटैचमेंट के साथ ईमेल भेजना अविश्वसनीय रूप से आसान होने के कारण मुश्किल से मुश्किल हो जाता है:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name'); //Name is optional
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$email->AddAddress( 'destinationaddress@example.com' );

$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';

$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

return $email->Send();

यह सिर्फ एक पंक्ति है $email->AddAttachment();- आप किसी भी आसान के लिए नहीं पूछ सकते।

यदि आप इसे PHP के mail()फ़ंक्शन के साथ करते हैं, तो आप कोड के ढेर लिख रहे होंगे, और आपको शायद कीड़े खोजने में बहुत मुश्किल होगी।


1
हाँ, यह आसान है। phpMailer की पूरी बात यह है कि यह जटिल चीजें करता है, ताकि आपके पास न हो। इसलिए यह पढ़ना जटिल है। यहां तक ​​कि केवल पाठ-केवल ईमेल भेजने के लिए, मैं phpMailer को प्राथमिकता देता हूं mail(), लेकिन संलग्नक के साथ काम करने के लिए यह एक पूर्ण नहीं ब्रेनर है ।
एसडीसी

4
मैं वही था - मेल का उपयोग करना चाहता था () सिर्फ इसलिए कि मेरे पास पहले से ही मेरे कोड में था। PHPMAILER ने मुझे अटैचमेंट भेजने में 5 मिनट से कम समय लिया!
जेम्स विल्सन

108
मैंने इस सवाल का जवाब पाया कि mail()अटैचमेंट को जोड़ने के लिए फ़ंक्शन का उपयोग कैसे करें । यह उत्तर मुझे ऐसा करने में मदद नहीं करता है।
साइपर

19
यह सवाल का जवाब नहीं है। PHPMailer के साथ अटैचमेंट कैसे भेजें, PHP के मेल () के साथ अटैचमेंट भेजने का तरीका नहीं है।
टॉबी

4
यह उत्तर परियोजना द्वारा उपयोग किए जाने वाले लाइसेंस की भी अनदेखी करता है। PHPMailer का उपयोग करके, आपको यह सुनिश्चित करना चाहिए कि आप अपने LGPL लाइसेंस के साथ समस्याओं को रोकने के लिए पैकेज को अपने स्रोत से बाहर कर दें।
एक्सल

190

आप निम्न कोड का उपयोग करके देख सकते हैं:

    $filename = 'myfile';
    $path = 'your path goes here';
    $file = $path . "/" . $filename;

    $mailto = 'mail@mail.com';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: name <test@test.com>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

14-June-2018 को संपादित करें

ईमेल प्रदाता के कुछ उपयोग में अधिक पठनीयता के लिए

$body .= $eol . $message . $eol . $eol; तथा $body .= $eol . $content . $eol . $eol;


$ uid अप्रयुक्त प्रतीत होता है।
एड।

किसी ने जवाब में बताया कि यह टिप्पणी होनी चाहिए कि चूंकि ओपी का कोड कहता है 'Example message with <b>html</b>', तो कंटेंट-टाइप के text/htmlबजाय होना चाहिए text/plain। मैं उसकी ओर से टिप्पणी पोस्ट कर रहा हूं क्योंकि उसके पास टिप्पणियों को पोस्ट करने के लिए पर्याप्त प्रतिनिधि नहीं है और मैंने विलोपन के लिए उत्तर को ध्वजांकित किया है।
आदि इनबार

इस कोड में, क्या आपको $ path और $ filename को परिभाषित करना है? और यह $ फ़ाइल नाम = $ _FILES ['उपयोगकर्ता नाम'] [[tmp_name ']] जैसा कुछ होगा; ?
malfy

$fileइसमें रेफर करने के बाद आप घोषणा क्यों करते हैं $filename?
कोलब कैन्यन

2
PHPMailer के डॉक्स से ... "ईमेल को सही ढंग से फ़ॉर्मेट करना आश्चर्यजनक रूप से कठिन है। असंख्य RFCs को ओवरलैप करने की आवश्यकता होती है, जिसके लिए जटिल जटिल प्रारूपण और एन्कोडिंग नियमों का कड़ाई से पालन आवश्यक है - कोड का विशाल बहुमत जो आपको ऑनलाइन मिलेगा जो मेल () फ़ंक्शन का सीधे उपयोग करता है। बस गलत है! " ...यह सच है! मैंने संलग्नक के साथ मेल भेजने के लिए इस उत्तर की तरह कुछ का उपयोग किया है और यह काम किया है! केवल कुछ दिनों के बाद ही पता चलता है कि जीमेल जहां अटैचमेंट को ठीक दिखाता है, वहीं अन्य प्रदाता मेल में इनबिल्ट कंटेंट को सीधे इनलाइन दिखाते हैं।
आरोन सिकलि

134

PHP 5.5.27 सुरक्षा अद्यतन के लिए

$file = $path.$filename;
$content = file_get_contents( $file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

// header
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";

// message & attachment
$nmessage = "--".$uid."\r\n";
$nmessage .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$nmessage .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$nmessage .= $message."\r\n\r\n";
$nmessage .= "--".$uid."\r\n";
$nmessage .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$nmessage .= $content."\r\n\r\n";
$nmessage .= "--".$uid."--";

if (mail($mailto, $subject, $nmessage, $header)) {
    return true; // Or do something here
} else {
  return false;
}

आपने $ फ़ाइल नाम को परिभाषित नहीं किया। यह क्या माना जाता है? फ़ाइलपथ?
जॉन

3
@Jon। $ फ़ाइल नाम, आपकी फ़ाइल का वास्तविक नाम है और फ़ाइल नाम के बिना $ पथ वास्तविक फ़ाइल पथ है। मैंने सोचा था कि चर वर्णनात्मक घोषित करने और उन्हें
व्यवस्थित

इसका मतलब किसी फंक्शन में होना है अगर आप उन्हें फंक्शन mail_attachment ($ filename, $ path, $ mailto, $ from_mail, $ from_name, $ replto, $ subject, $ message) परिभाषित करना चाहते हैं
जॉन

3
एकाधिक संलग्नक भेजने वालों के लिए ध्यान दें - $nmessage .= "--".$uid."\r\n";अंतिम MIME भागों के साथ अलग-अलग MIME भागों का उपयोग करें, $nmessage .= "--".$uid."--";(जैसा कि ऊपर दिखाया गया है)।
रिनोगो

2
यह अंततः बेवकूफ phpmailer काम करने की कोशिश कर के सिरदर्द के बाद काम किया।
ई। एरूड

22

स्विफ्टमेलर एक और आसान उपयोग वाली स्क्रिप्ट है जो स्वचालित रूप से ईमेल इंजेक्शन से बचाता है और अटैचमेंट्स को हवा देता है। PHP के अंतर्निहित mail()फ़ंक्शन का उपयोग करके मैं दृढ़ता से हतोत्साहित करता हूं ।

काम में लाना:

  • स्विफ्टमेलर डाउनलोड करें , और libअपने प्रोजेक्ट में फ़ोल्डर रखें
  • का उपयोग कर मुख्य फ़ाइल को शामिल करें require_once 'lib/swift_required.php';

अब जब आपको मेल करना हो तो कोड जोड़ें:

// Create the message
$message = Swift_Message::newInstance()
    ->setSubject('Your subject')
    ->setFrom(array('webmaster@mysite.com' => 'Web Master'))
    ->setTo(array('receiver@example.com'))
    ->setBody('Here is the message itself')
    ->attach(Swift_Attachment::fromPath('myPDF.pdf'));

//send the message          
$mailer->send($message);

अधिक जानकारी और विकल्प स्विफ्टमेलर डॉक्स में देखे जा सकते हैं ।


6
क्योंकि आप थ्री-पार्टी लाइब्रेरी को
ड्वॉन्लोड

क्या PHPMailer 3rd-party नहीं है? या मतलब @MatthewJohnson बनाया या स्विफ्टमेलर के मुख्य अंश का हिस्सा है? या तो जब तक समाधान अच्छा और प्रभावी है, तब तक एक डाउनवोट अनुपयोगी होगा ...
Xsmael

1
@ Xsmael, PHPMailer निश्चित रूप से 3rd पार्टी है :) मैं डाउनवोट्स से असहमत हूं, (कम से कम उस समय) समाधान काम करता है। हालाँकि, लोग अपनी इच्छानुसार मतदान कर सकते हैं, और चढ़ाव को नकारात्मकता से अधिक बढ़ाते हैं।
मैथ्यू जॉनसन

17

संलग्नक के साथ एक ईमेल भेजने के लिए हमें मल्टीपार्ट / मिश्रित MIME प्रकार का उपयोग करना होगा जो निर्दिष्ट करता है कि मिश्रित प्रकार ईमेल में शामिल किए जाएंगे। इसके अलावा, हम ईमेल के दोनों सादे-पाठ और HTML संस्करण भेजने के लिए मल्टीपार्ट / वैकल्पिक MIME प्रकार का उपयोग करना चाहते हैं। उदाहरण के लिए एक नज़र डालें:

<?php 
//define the receiver of the email 
$to = 'youraddress@example.com'; 
//define the subject of the email 
$subject = 'Test email with attachment'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n 
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
//add boundary string and mime type specification 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip'))); 
//define the body of the message. 
ob_start(); //Turn on output buffering 
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

--PHP-alt-<?php echo $random_hash; ?>-- 

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

<?php echo $attachment; ?> 
--PHP-mixed-<?php echo $random_hash; ?>-- 

<?php 
//copy current buffer contents into $message variable and delete current output buffer 
$message = ob_get_clean(); 
//send the email 
$mail_sent = @mail( $to, $subject, $message, $headers ); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
?>

जैसा कि आप देख सकते हैं, अनुलग्नक के साथ एक ईमेल भेजना पूरा करना आसान है। पूर्ववर्ती उदाहरण में हमारे पास मल्टीमेड / मिश्रित MIME प्रकार है, और इसके अंदर हमारे पास मल्टीपार्ट / वैकल्पिक MIME प्रकार है जो ईमेल के दो संस्करणों को निर्दिष्ट करता है। हमारे संदेश के लिए एक लगाव को शामिल करने के लिए, हम निर्दिष्ट फ़ाइल से डेटा को एक स्ट्रिंग में पढ़ते हैं, इसे बेस 64 के साथ एनकोड करते हैं, इसे छोटे विखंडू में विभाजित करते हैं ताकि यह सुनिश्चित हो सके कि यह माइम विनिर्देशों से मेल खाता है और फिर इसे अनुलग्नक के रूप में शामिल करें।

यहां से ले गए ।


15
ओपी टिप्पणियों में जोड़े गए लिंक में सामग्री की कॉपी / पेस्ट
मार्क

अच्छा स्निपेट, हालांकि मुझे इसे काम करने के लिए सीमा स्ट्रिंग के बाद एक अतिरिक्त न्यूलाइन प्रदान करना था। मुझे लगता है कि यह php फ़ाइल के लाइन अंत के साथ कुछ करना है अनुमान लगा रहा हूँ। मेरा संपादक एलएफ के लिए चूक करता है, लेकिन मुझे लगता है कि मानक को उम्मीद है कि गाड़ी वापसी (सीआरएलएफ) होगी।
ऑगियर स्केल्विस

9

यह मेरे लिए काम करता है। यह कई अटैचमेंट भी देता है। सरलता

<?php

if ($_POST && isset($_FILES['file'])) {
    $recipient_email = "recipient@yourmail.com"; //recepient
    $from_email = "info@your_domain.com"; //from email using site domain.
    $subject = "Attachment email from your website!"; //email subject line

    $sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING); //capture sender name
    $sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
    $sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
    $attachments = $_FILES['file'];

    //php validation
    if (strlen($sender_name) < 4) {
        die('Name is too short or empty');
    }
    if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email');
    }
    if (strlen($sender_message) < 4) {
        die('Too short message! Please enter something');
    }

    $file_count = count($attachments['name']); //count total files attached
    $boundary = md5("specialToken$4332"); // boundary token to be used

    if ($file_count > 0) { //if attachment exists
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:" . $from_email . "\r\n";
        $headers .= "Reply-To: " . $sender_email . "" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

        //message text
        $body = "--$boundary\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($sender_message));

        //attachments
        for ($x = 0; $x < $file_count; $x++) {
            if (!empty($attachments['name'][$x])) {

                if ($attachments['error'][$x] > 0) { //exit script and output error if we encounter any
                    $mymsg = array(
                        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
                        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                        3 => "The uploaded file was only partially uploaded",
                        4 => "No file was uploaded",
                        6 => "Missing a temporary folder");
                    die($mymsg[$attachments['error'][$x]]);
                }

                //get file info
                $file_name = $attachments['name'][$x];
                $file_size = $attachments['size'][$x];
                $file_type = $attachments['type'][$x];

                //read file 
                $handle = fopen($attachments['tmp_name'][$x], "r");
                $content = fread($handle, $file_size);
                fclose($handle);
                $encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)

                $body .= "--$boundary\r\n";
                $body .= "Content-Type: $file_type; name=" . $file_name . "\r\n";
                $body .= "Content-Disposition: attachment; filename=" . $file_name . "\r\n";
                $body .= "Content-Transfer-Encoding: base64\r\n";
                $body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
                $body .= $encoded_content;
            }
        }
    } else { //send plain email otherwise
        $headers = "From:" . $from_email . "\r\n" .
                "Reply-To: " . $sender_email . "\n" .
                "X-Mailer: PHP/" . phpversion();
        $body = $sender_message;
    }

    $sentMail = @mail($recipient_email, $subject, $body, $headers);
    if ($sentMail) { //output success or failure messages
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');
    }
}
?>

यह कोड उपयोगकर्ता इनपुट के सत्यापन और उचित प्रासंगिक भागने की कमी के कारण हेडर इंजेक्शन हमलों के लिए असुरक्षित है।
सिंक्रो

@Synchro .. यह एकमात्र कोड है जो मुझे कई अटैचमेंट के लिए मिला है जो मेरे लिए काम करते हैं .. क्या आप कृपया सुझाव दे सकते हैं कि इसे सुरक्षित तरीके से कैसे उपयोग किया जाए।
नमाथुर

7

बुरी तरह से स्वरूपित अनुलग्नकों के साथ कुछ समय तक संघर्ष करने के बाद, यह वह कोड है जिसका मैंने उपयोग किया था:

$email = new PHPMailer();
$email->From      = 'from@somedomain.com';
$email->FromName  = 'FromName';
$email->Subject   = 'Subject';
$email->Body      = 'Body';
$email->AddAddress( 'to@somedomain.com' );
$email->AddAttachment( "/path/to/filename.ext" , "filename.ext", 'base64', 'application/octet-stream' );
$email->Send();

6

कार्य अवधारणा:

if (isset($_POST['submit'])) {
    $mailto = $_POST["mailTo"];
    $from_mail = $_POST["fromEmail"];
    $replyto = $_POST["fromEmail"];
    $from_name = $_POST["fromName"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    $filename = $_FILES["fileAttach"]["name"];
    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";

    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--" . $uid . "\r\n";

// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
    $header .= "Content-type:text/html; charset=utf-8\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

// User Message you can add HTML if You Selected HTML content
    $header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";

    $header .= "--" . $uid . "\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
    $header .= $content . "\r\n\r\n";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
        echo "<script>alert('Success');</script>"; // or use booleans here
    } else {
        echo "<script>alert('Failed');</script>";
    }
}

6

उपर्युक्त उत्तरों में से कोई भी उनके निर्दिष्ट अनुलग्नक प्रारूप ( application/octet-stream) के कारण मेरे लिए काम नहीं करता है । application/pdfपीडीएफ फाइलों के साथ सर्वोत्तम परिणामों के लिए उपयोग करें ।

<?php

// just edit these 
$to          = "email1@domain.com, email2@domain.com"; // addresses to email pdf to
$from        = "sent_from@domain.com"; // address message is sent from
$subject     = "Your PDF email subject"; // email subject
$body        = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName     = "pdf-file.pdf"; // pdf file name recipient will get
$filetype    = "application/pdf"; // type

// creates headers and mime boundary
$eol = PHP_EOL;
$semi_rand     = md5(time());
$mime_boundary = "==Multipart_Boundary_$semi_rand";
$headers       = "From: $from$eolMIME-Version: 1.0$eol" .
    "Content-Type: multipart/mixed;$eol boundary=\"$mime_boundary\"";

// add html message body
$message = "--$mime_boundary$eol" .
    "Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
    "Content-Transfer-Encoding: 7bit$eol$eol$body$eol";

// fetches pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));

// attaches pdf to email
$message .= "--$mime_boundary$eol" .
    "Content-Type: $filetype;$eol name=\"$pdfName\"$eol" .
    "Content-Disposition: attachment;$eol filename=\"$pdfName\"$eol" .
    "Content-Transfer-Encoding: base64$eol$eol$pdf$eol--$mime_boundary--";

// Sends the email
if(mail($to, $subject, $message, $headers)) {
    echo "The email was sent.";
}
else {
    echo "There was an error sending the mail.";
}

$ हेडर = "से: $ $ eolMIME- संस्करण: 1.0 $ eol" $ eolMIME पर अपरिभाषित चर त्रुटि को फेंकता रहता है।
हटना

हम्म ... के "From: $from$eolMIME-Version: 1.0$eol"साथ बदलें"From: $from" . "$eolMIME-Version: 1.0$eol"
omikes

हो सकता है कि यह आपको दो चर जोड़ने न दे जैसे कि php के कुछ संस्करणों में, यह उस पर काम करता है जिस पर मैं उपयोग कर रहा था। उसके लिए माफ़ करना। वास्तव में इतने सारे घटनाओं आप के सभी उदाहरणों को बदलने के लिए चाहते हो सकता है देखते हैं $eolके साथ " . "$eolकि जिस तरह से अपने सभी किया एक स्वूप गिर गया में।
omikes

2
            $to = "to@gmail.com";
            $subject = "Subject Of The Mail";
            $message = "Hi there,<br/><br/>This is my message.<br><br>";

            $headers = "From: From-Name<from@gmail.com>";
// boundary
            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// headers for attachment
            $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

// multipart boundary
            $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=ISO-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";

                $message .= "--{$mime_boundary}\n";
                $filepath = 'uploads/'.$_FILES['image']['name'];
                move_uploaded_file($_FILES['image']['tmp_name'], $filepath); //upload the file
                $filename = $_FILES['image']['name'];
                $file = fopen($filepath, "rb");
                $data = fread($file, filesize($filepath));
                fclose($file);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$filename\"\n" .
                        "Content-Disposition: attachment;\n" . " filename=\"$filename\"\n" .
                        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                $message .= "--{$mime_boundary}\n";

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

2

HTML कोड:

<form enctype="multipart/form-data" method="POST" action=""> 
    <label>Your Name <input type="text" name="sender_name" /> </label> 
    <label>Your Email <input type="email" name="sender_email" /> </label> 
    <label>Your Contact Number <input type="tel" name="contactnumber" /> </label>
    <label>Subject <input type="text" name="subject" /> </label> 
    <label>Message <textarea name="description"></textarea> </label> 
    <label>Attachment <input type="file" name="attachment" /></label> 
    <label><input type="submit" name="button" value="Submit" /></label> 
</form> 

PHP कोड:

<?php
if($_POST['button']){
{
    //Server Variables
    $server_name = "Your Name";
    $server_mail = "your_mail@domain.com";

    //Name Attributes of HTML FORM
    $sender_email = "sender_email";
    $sender_name = "sender_name";
    $contact = "contactnumber";
    $mail_subject = "subject";
    $input_file = "attachment";
    $message = "description";

    //Fetching HTML Values
    $sender_name = $_POST[$sender_name];
    $sender_mail = $_POST[$sender_email];
    $message = $_POST[$message];
    $contact= $_POST[$contact];
    $mail_subject = $_POST[$mail_subject];

    //Checking if File is uploaded
    if(isset($_FILES[$input_file])) 
    { 
        //Main Content
        $main_subject = "Subject seen on server's mail";
        $main_body = "Hello $server_name,<br><br> 
        $sender_name ,contacted you through your website and the details are as below: <br><br> 
        Name : $sender_name <br> 
        Contact Number : $contact <br> 
        Email : $sender_mail <br> 
        Subject : $mail_subject <br> 
        Message : $message.";

        //Reply Content
        $reply_subject = "Subject seen on sender's mail";
        $reply_body = "Hello $sender_name,<br> 
        \t Thank you for filling the contact form. We will revert back to you shortly.<br><br>
        This is an auto generated mail sent from our Mail Server.<br>
        Please do not reply to this mail.<br>
        Regards<br>
        $server_name";

//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
        $filename= $_FILES[$input_file]['name'];
        $file = chunk_split(base64_encode(file_get_contents($_FILES[$input_file]['tmp_name'])));
        $uid = md5(uniqid(time()));
        //Sending mail to Server
        $retval = mail($server_mail, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n $main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
        //Sending mail to Sender
        $retval = mail($sender_mail, $reply_subject, $reply_body , "From: $server_name<$server_mail>\r\nMIME-Version: 1.0\r\nContent-type: text/html\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################

        //Output
        if ($retval == true) {
            echo "Message sent successfully...";
            echo "<script>window.location.replace('index.html');</script>";
        } else {
            echo "Error<br>";
            echo "Message could not be sent...Try again later";
            echo "<script>window.location.replace('index.html');</script>";
        }
    }else{
        echo "Error<br>";
        echo "File Not Found";
    }
}else{
    echo "Error<br>";
    echo "Unauthorised Access";
}

1

मैंने अपना ईमेल भेजने / एन्कोडिंग फ़ंक्शन लिखना समाप्त कर दिया। पीडीएफ अटैचमेंट भेजने के लिए इसने मेरे लिए अच्छा काम किया है। मैंने उत्पादन में अन्य विशेषताओं का उपयोग नहीं किया है।

नोट: कल्पना काफी सशक्त होने के बावजूद कि आपको हेडर को अलग करने के लिए \ n \ n का उपयोग करना चाहिए, मैंने पाया कि यह केवल तभी काम करता है जब मैंने PHP_EOL का उपयोग किया था। मैंने केवल लिनक्स पर इसका परीक्षण किया है। YMMV

<?php
# $args must be an associative array
#     required keys: from, to, body
#          body can be a string or a [tree of] associative arrays. See examples below
#     optional keys: subject, reply_to, cc, bcc
# EXAMPLES:
#    # text-only email:
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => 'Hi, testing 1 2 3',
#    ));
#
#    # html-only email
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/html because we're passing a string that starts with '<'
#        'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
#    ));
#
#    # text-only email (explicitly, in case first character is dynamic or something)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => array(
#            'type' => 'text',
#            'body' => $message_text,
#        )
#    ));
#
#    # email with text and html alternatives (auto-detected mime types)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                "Hi!\n\nI like cheese",
#                '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
#            )
#        )
#    ));
#
#    # email with text and html alternatives (explicit types)
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                array(
#                    'type' => 'text',
#                    'body' => "Hi!\n\nI like cheese",
#                ),
#                array(
#                    'type' => 'html',
#                    'body' => '<h1>Hi!</h1><p>I like cheese</p>',
#                ),
#            )
#        )
#    ));
#
#    # email with an attachment
#    email2(array(
#        'from' => 'noreply@foo.com',
#        'to' => 'jason@jasonwoof.com',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'mixed',
#            'body' => array(
#                "Hi!\n\nCheck out this (inline) image",
#                array(
#                    'type' => 'image/png',
#                    'disposition' => 'inline',
#                    'body' => $image_data, # raw file contents
#                ),
#                "Hi!\n\nAnd here's an attachment",
#                array(
#                    'type' => 'application/pdf; name="attachment.pdf"',
#                    'disposition' => 'attachment; filename="attachment.pdf"',
#                    'body' => $pdf_data, # raw file contents
#                ),
#                "Or you can use shorthand:",
#                array(
#                    'type' => 'application/pdf',
#                    'attachment' => 'attachment.pdf', # name for client (not data source)
#                    'body' => $pdf_data, # raw file contents
#                ),
#            )
#        )
#    ))
function email2($args) {
    if (!isset($args['from'])) { return 1; }
    $from = $args['from'];
    if (!isset($args['to'])) { return 2; }
    $to = $args['to'];
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
    $cc = isset($args['cc']) ? $args['cc'] : '';
    $bcc = isset($args['bcc']) ? $args['bcc'] : '';

    #FIXME should allow many more characters here (and do Q encoding)
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

    $headers = "From: $from";
    if($reply_to) {
        $headers .= PHP_EOL . "Reply-To: $reply_to";
    }
    if($cc) {
        $headers .= PHP_EOL . "CC: $cc";
    }
    if($bcc) {
        $headers .= PHP_EOL . "BCC: $bcc";
    }

    $r = email2_helper($args['body']);
    $headers .= PHP_EOL . $r[0];
    $body = $r[1];

    if (mail($to, $subject, $body, $headers)) {
        return 0;
    } else {
        return 5;
    }
}

function email2_helper($body, $top = true) {
    if (is_string($body)) {
        if (substr($body, 0, 1) == '<') {
            return email2_helper(array('type' => 'html', 'body' => $body), $top);
        } else {
            return email2_helper(array('type' => 'text', 'body' => $body), $top);
        }
    }
    # now we can assume $body is an associative array
    # defaults:
    $type = 'application/octet-stream';
    $mime = false;
    $boundary = null;
    $disposition = null;
    $charset = false;
    # process 'type' first, because it sets defaults for others
    if (isset($body['type'])) {
        $type = $body['type'];
        if ($type === 'text') {
            $type = 'text/plain';
            $charset = true;
        } elseif ($type === 'html') {
            $type = 'text/html';
            $charset = true;
        } elseif ($type === 'alternative' || $type === 'alternatives') {
            $mime = true;
            $type = 'multipart/alternative';
        } elseif ($type === 'mixed') {
            $mime = true;
            $type = 'multipart/mixed';
        }
    }
    if (isset($body['disposition'])) {
        $disposition = $body['disposition'];
    }
    if (isset($body['attachment'])) {
        if ($disposition == null) {
            $disposition = 'attachment';
        }
        $disposition .= "; filename=\"{$body['attachment']}\"";
        $type .= "; name=\"{$body['attachment']}\"";
    }
    # make headers
    $headers = array();
    if ($top && $mime) {
        $headers[] = 'MIME-Version: 1.0';
    }
    if ($mime) {
        $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
        $type .= "; boundary=$boundary";
    }
    if ($charset) {
        $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
    }
    $headers[] = "Content-Type: $type";
    if ($disposition !== null) {
        $headers[] = "Content-Disposition: {$disposition}";
    }

    $data = '';
    # return array, first el is headers, 2nd is body (php's mail() needs them separate)
    if ($mime) {
        foreach ($body['body'] as $sub_body) {
            $data .= "--$boundary" . PHP_EOL;
            $r = email2_helper($sub_body, false);
            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
        }
        $data .= "--$boundary--";
    } else {
        if(preg_match('/[^\x09\x0A\x0D\x20-\x7E]/', $body['body'])) {
            $headers[] = "Content-Transfer-Encoding: base64";
            $data .= chunk_split(base64_encode($body['body']));
        } else {
            $data .= $body['body'];
        }
    }
    return array(join(PHP_EOL, $headers), $data);
}

मुझे बस एहसास हुआ कि मेरे कोड ने कुछ फ़ंक्शंस को बुलाया था जिसमें मैंने शामिल नहीं किया था। उन्होंने सिर्फ यह सुनिश्चित किया कि / से / cc / etc मान वैध थे। मैंने उन्हें हटा दिया, और अब यह कोड अपने आप ही काम करता है।
जेसनवॉफ

-1

इस पृष्ठ से कोड कॉपी करना - मेल में काम करता है ()

वह एक फंक्शन mail_attachment बनाना शुरू करता है जिसे बाद में कहा जा सकता है। जिसे वह बाद में अपने अटैचमेंट कोड के साथ करता है।

<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}

//start editing and inputting attachment details here
$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "my@mail.com";
$my_replyto = "my_reply_to@mail.net";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "recipient@mail.org", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>

उनके पेज पर अधिक विवरण हैं और टिप्पणी अनुभाग में कुछ समस्याओं का जवाब देते हैं।


-1

Php में लगाव के साथ ईमेल भेजने के लिए 100% काम करने की अवधारणा:

if (isset($_POST['submit'])) {
  extract($_POST);
  require_once('mail/class.phpmailer.php');

  $subject = "$name Applied For - $position";
  $email_message = "<div>Thanks for Applying ....</div> ";

  $mail = new PHPMailer;
  $mail->IsSMTP(); // telling the class to use SMTP
  $mail->Host = "mail.companyname.com"; // SMTP server
  $mail->SMTPDebug = 0;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = "ssl";
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->IsHTML(true);
  $mail->Username = "info@companyname.com";  // GMAIL username
  $mail->Password = "mailPassword";          // GMAIL password

  $mail->SetFrom('info@companyname.com', 'new application submitted');
  $mail->AddReplyTo("name@yourdomain.com","First Last");
  $mail->Subject = "your subject";

  $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

  $mail->MsgHTML($email_message);

  $address = 'info@companyname.com';
  $mail->AddAddress($address, "companyname");

  $mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);      // attachment

  if (!$mail->Send()) {
    /* Error */
    echo 'Message not Sent! Email at info@companyname.com';
  } else {
    /* Success */
    echo 'Sent Successfully! <b> Check your Mail</b>';
  }
}

मैंने इस कोड का इस्तेमाल अटैचमेंट के साथ google smtp मेल भेजने के लिए किया था ...।

नोट: PHPMailer लाइब्रेरी को यहाँ से डाउनलोड करें -> https://github.com/PHPMailer/PHPMailer

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.