Hi there,

I'm really sorry for posting on here, I normally try to work things out myself and plod through, so sorry for taking your time. I write in PHP for fun, I'm no expert, but I manage to make a nice webpage with good MySQL functionality and some PHP in there to make things easier and more effective.

I'm currently adding an option where people can send me calendar invites and I've created the .ics file already, thats not been a problem. The problem is when I try to send it as an attachment, I just can't get it to come through.

Now this code looks messy, which is due to taking other peoples examples from the net and trying to incorporate them in my code. For now, I just want to get it working first and then I can tidy it up and place things in includes etc...

Any help would be greatly appreciated, I think the problem is in the headers, but can't work it out.


if (!is_array($_POST))
    return;
reset($_POST);

while(list($key, $val) = each($_POST)) {
    $GLOBALS[$key] = stripslashes($val);
    $val=stripslashes($val);
}

// Is there an email address? Should be...
$MailFormEmail_new = $MailFormEmail;
    if (!$MailFormEmail_new) {
    $MailFormEmail_new = "noemailadress@nowhere.com";
    }

// Compile the message to us
$Message .= 
"
Company:
$MailFormCompany\n
Sender:
$MailFormName\n
Contact number:
$MailFormNumber\n
Email:
$MailFormEmail_new\n
Query:
$MailFormQuery\n
Query orignated:
IP: $MailFormIP
HTTP Origin: $MailFormHTTPref
HTTP Agent: $MailFormHTTPagent
";

// Who's it going to and what Subject?
$MailFormToAddress = "me@me.com";
$MailFormSubject = "Online Enquiry from ".$MailFormName." (".$MailFormCompany.")";

// Header and footer of email
$Header = "Hi there!\nYou have received an online enquiry from ".$MailFormName." of ".$MailFormCompany."\n\nThe Message was sent at ".date("H:i")." on ".date("l dS \of F Y O");

$Footer = "Please have a look and contact them as soon as possible.\n\nKind Regards\nYour Website\n";

if ($Header) {
$Message = $Header."\n\n".$Message;
}

if ($Footer) {
$Message .= "\n\n".$Footer;
}

$uid          = "sjt64vqadlhlb1j8edi18oeelo@google.com";
$datestampnow = date("Ymd") . "T" . date("Hms")."Z";
$startdate    = "20110201T100000Z";
$enddate      = "20110201T103000Z";
$desc         = "Description box";
$summary      = "Summary box";
// Now create calendar file

$myFile = "dispatch.ics";

$fh = fopen("$myFile", "x+");

$icscard = sprintf("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Google Inc//Google Calendar 70.9054//EN\nMETHOD:PUBLISH\nVERSION:2.0\n
CALSCALE:GREGORIAN\nBEGIN:VEVENT\nDTSTART:%s\nDTEND:%s\nDTSTAMP:%s\nCREATED:%sUID:%s\nDESCRIPTION:%s\nLAST-MODIFIED:%s\nLOCATION:\nSEQUENCE:0\nSUMMARY:%s\nTRANSP:OPAQUE\nEND:VEVENT\nEND:VCALENDAR\n",
    $startdate,
    $enddate,
    $datestampnow,
    $datestampnow,
    $uid,
    $desc,
    $datestampnow, 
    $summary);

str_replace("\t", "", $icscard);

fwrite($fh, $icscard);
fclose($fh);

$Message->Attach[] = array(
	'content' => $icscard, 
	'type' => 'text/calendar', 
	'name' => 'dispatch.ics',
	'charset' => 'utf-8',
	'encoding' => 'base64'
);

// End creation of calendar file


// Now create email headers
$random_hash = md5(date('r', time()));
$header = "From: $MailFormEmail_new";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=0003255584f2a0934e04995f9d4a";

// You have mail!
mail( "$MailFormToAddress", "$MailFormSubject", "$Message", "$headers");

unset($myFile);

Thank you.

    You are calling

    $Message->Attach

    to attach the file, but $Message is a string, not an object, and as such does not have an Attach property.

    I think doing this with the mail() function will make this needlessly difficult, what you need is PEAR Mail. This will help avoid mail being eaten by spam filters as well, as you send via an SMTP server with auth.

      DaveRandom;10972940 wrote:

      You are calling

      $Message->Attach

      to attach the file, but $Message is a string, not an object, and as such does not have an Attach property.

      I think doing this with the mail() function will make this needlessly difficult, what you need is PEAR Mail. This will help avoid mail being eaten by spam filters as well, as you send via an SMTP server with auth.

      Thanks Dave,

      I've actually got this working now, but trying to do it with SMTP authentication, just having issues with my server.

      They annoying thing is, before I had it so the invite showed in gmail at the top of the email so I could just accept it, there was no file attachment, just the calendar invite kinda embedded in the email.

      I've lost that now and no idea how I got it there in the first place. Don't suppose you have any idea's do you how to get that functionality?

        DaveRandom;10972958 wrote:

        maybe this will help you?

        Hi Dave,

        Thanks for taking the time to look. I'd looked at that part previously, but found it quite difficult to implement into my code.

        At the minute I have two versions. One that embeds the calendar appointment into the email so Googlemail will load it at the top of the page.

        Another that emails a file called dispatch.ics and sends that to me as an email.

        I can't seem to get the email to do both. I've tried and got the below code, but it only seems to embed the calendar appointment, not adding in the file too. Any ideas?

        function sendIcalEmail($firstname,$lastname,$email,$meeting_date,$meeting_name,$meeting_duration) {
        
        $from_name = "My Name";
        $from_address = "myname@mydomain.com";
        $subject = "Meeting Booking"; //Doubles as email subject and meeting subject in calendar
        $meeting_description = "Here is a brief description of my meeting\n\n";
        $meeting_location = "My Office"; //Where will your meeting take place
        
        
        //Convert MYSQL datetime and construct iCal start, end and issue dates
        $meetingstamp = strtotime($meeting_date . " UTC");    
        $dtstart= gmdate("Ymd\THis\Z",$meetingstamp);
        $dtend= gmdate("Ymd\THis\Z",$meetingstamp+$meeting_duration);
        $todaystamp = gmdate("Ymd\THis\Z");
        
        //Create unique identifier
        $cal_uid = date('Ymd').'T'.date('His')."-".rand()."@mydomain.com";
        
        //Create Mime Boundry
        $mime_boundary = "----Meeting Booking----".md5(time());
        
        //Create Email Headers
        $headers = "From: ".$from_name." <".$from_address.">\n";
        $headers .= "Reply-To: ".$from_name." <".$from_address.">\n";
        
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
        $headers .= "Content-class: urn:content-classes:calendarmessage\n";
        // Embed Starts here
        //Create Email Body (HTML)
        $message .= "--$mime_boundary\n";
        $message .= "Content-Type: text/html; charset=UTF-8\n";
        $message .= "Content-Transfer-Encoding: 8bit\n\n";
        
        $message .= "<html>\n";
        $message .= "<body>\n";
        $message .= '<p>Dear '.$firstname.' '.$lastname.',</p>';
        $message .= '<p>Here is my HTML Email / Used for Meeting Description</p>';    
        $message .= "</body>\n";
        $message .= "</html>\n";
        $message .= "--$mime_boundary\n";
        
        //Create ICAL Content (Google rfc 2445 for details and examples of usage) 
        $ical =    'BEGIN:VCALENDAR
        PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
        VERSION:2.0
        METHOD:PUBLISH
        BEGIN:VEVENT
        ORGANIZER:MAILTO:'.$from_address.'
        DTSTART:'.$dtstart.'
        DTEND:'.$dtend.'
        LOCATION:'.$meeting_location.'
        TRANSP:OPAQUE
        SEQUENCE:0
        UID:'.$cal_uid.'
        DTSTAMP:'.$todaystamp.'
        DESCRIPTION:'.$meeting_description.'
        SUMMARY:'.$subject.'
        PRIORITY:5
        CLASS:PUBLIC
        END:VEVENT
        END:VCALENDAR';   
        
        $message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n';
        $message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST\n';
        $message .= "Content-Transfer-Encoding: 8bit\n\n";
        $message .= $ical;       
        //	$message .= '--$mime_boundary--\n';      
        // End of Embed calendar appointment // Right, now add the file $fileatt = 'dispatch.ics'; // Path to the file $fileatt_type = "text/calendar"; // File Type $fileatt_name = 'dispatch.ics'; // Filename that will be used for the file as the attachment $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary2 = "==Multipart_Boundary_x{$semi_rand}x"; $message .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary2}\""; $message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary2}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n"."File Attachment should be below\n\n"; $data = chunk_split(base64_encode($data)); $message .= "--{$mime_boundary2}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary2}--\n"; //SEND MAIL $mail_sent = @mail( $email, $subject, $message, $headers ); if($mail_sent) { return true; } else { return false; } }

          Try using this function I've just knocked up (based heavily on the link posted before)...

          function mail_attachments ($to, $subject, $body, $attachments, $headers = FALSE, $mailparams = FALSE) {
            $mixedboundary = 'boundary-mixed-'.($random_hash = md5(time()));
            if (!$headers) $headers = array(); else foreach ($headers as $header => $data) if (strtolower($header) == 'content-type') unset($headers[$header]);
            $headers['Content-Type'] = "multipart/mixed; boundary=\"$mixedboundary\"";
            $headersarr = array();
            foreach ($headers as $header => $data) $headersarr[] = "$header: $data";
            $headerstr = implode("\r\n",$headersarr);
            $bodystr = "--$mixedboundary\r\n";
            if (isset($body['html']) && isset($body['text'])) {
              $bodystr .= "Content-Type: multipart/alternative; boundary=\"".($altboundary = "boundary-alt-$random_hash")."\"\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['text']."\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['html']."\r\n\r\n--$altboundary--\r\n\r\n--$mixedboundary";
            } else if (($html = isset($body['html'])) || isset($body['text'])) {
              $bodystr .= "Content-Type: text/".(($html) ? 'html' : 'plain')."; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".(($html) ? $body['html'] : $body['text'])."\r\n\r\n--$mixedboundary";
            } else return FALSE;
            foreach ($attachments as $attachment => $type) if (is_file($attachment)) $bodystr .= "\r\nContent-Type: $type; name=\"".basename($attachment)."\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment\r\n\r\n".chunk_split(base64_encode(file_get_contents($attachment)))."\r\n--$mixedboundary";
            $bodystr .= "--";  print($bodystr."\r\n\r\nHeaders:\r\n".$headerstr);
            return ($mailparams) ? @mail($to,$subject,$bodystr,$headerstr,$mailparams) : @mail($to,$subject,$bodystr,$headerstr);
          }

          I haven't tested it but I reckon it should work.

          $to is a string, just like mail()

          $subject is a string, just like mail()

          $body is an associative array. At least one of $body['text'] and $body['html'] MUST be set (for you, I think you will just put the body of your message in $body['html']). You can set both, but not niether.

          $attachments is an associative array, in the form

          array ( '/path/to/attachment'=>'mimetype/of-attachment' )

          Set as many attachments as you like, but they MUST be local files (so you can just dump the file have created to a temp file, and pass the path to that temp file).

          $headers is an associative array, in the form

          array( 'header' => 'Value of header' )

          Set as many headers as you like.

          $mailparams is a string, just like the last parameter of mail()

          Returns a Boolean, like mail()

          Let me know how you get on 🙂

          PS apologies for the lack of comments in that code, I will pretty it up when I know it works...

            Try this:

            <?php
            
              function sendIcalEmail ($firstname,$lastname,$email,$meeting_date,$meeting_name,$meeting_duration) { 
            
            $from_name = "My Name"; 
            $from_address = "myname@mydomain.com"; 
            $subject = "Meeting Booking"; //Doubles as email subject and meeting subject in calendar 
            $meeting_description = "Here is a brief description of my meeting\n\n"; 
            $meeting_location = "My Office"; //Where will your meeting take place 
            
            //Convert MYSQL datetime and construct iCal start, end and issue dates 
            $meetingstamp = strtotime($meeting_date . " UTC");     
            $dtstart= gmdate("Ymd\THis\Z",$meetingstamp); 
            $dtend= gmdate("Ymd\THis\Z",$meetingstamp+$meeting_duration); 
            $todaystamp = gmdate("Ymd\THis\Z"); 
            
            //Create unique identifier 
            $cal_uid = date('Ymd').'T'.date('His')."-".rand()."@mydomain.com"; 
            
            //Create Email Headers 
            $headers = array (
              "From" => "$from_name <$from_address>", 
              "Reply-To" => "$from_name <$from_address>", 
              "MIME-Version" => "1.0"
            );
            
            //Create Email Body (HTML) 
            $body = "<html>\r\n<body>\r\n<p>Dear $firstname $lastname,</p>\r\n<p>Here is my HTML Email / Used for Meeting Description</p>\r\n</body>\r\n</html>"; 
            
            //Create ICAL Content (Google rfc 2445 for details and examples of usage) 
            $ical = "BEGIN:VCALENDAR
            PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
            VERSION:2.0
            METHOD:PUBLISH
            BEGIN:VEVENT
            ORGANIZER:MAILTO:$from_address
            DTSTART:$dtstart
            DTEND:$dtend
            LOCATION:$meeting_location
            TRANSP:OPAQUE
            SEQUENCE:0
            UID:$cal_uid
            DTSTAMP:$todaystamp
            DESCRIPTION:$meeting_description
            SUMMARY:$subject
            PRIORITY:5
            CLASS:PUBLIC
            END:VEVENT
            END:VCALENDAR";    
            
            // Define data about the attachment
            $fileatt = 'dispatch.ics'; // Path to the file 
            $fileatt_type = "text/calendar"; // File Type 
            $attachments = array($fileatt => $fileatt_type);
            
            // write ICAL to file
            file_put_contents($fileatt,$ical);
            
            //SEND MAIL 
            return mail_attachments( $email, $subject, $body, $attachments, $headers ); 
            
              }
            
              function mail_attachments ($to, $subject, $body, $attachments, $headers = FALSE, $mailparams = FALSE) {
                // Get random hash and define first boundary string
                $mixedboundary = 'boundary-mixed-'.($random_hash = md5(time()));
                // Validate $headers, unset the content-type if it is set and overwrite it with multipart/mixed
                if (!$headers) $headers = array(); else foreach ($headers as $header => $data) if (strtolower($header) == 'content-type') unset($headers[$header]);
                $headers['Content-Type'] = "multipart/mixed; boundary=\"$mixedboundary\"";
                // Build extra headers into a string
                $headersarr = array();
                foreach ($headers as $header => $data) $headersarr[] = "$header: $data";
                $headerstr = implode("\r\n",$headersarr);
                // Start building body
                $bodystr = "--$mixedboundary\r\n";
                if (is_array($body)) {
                  if (isset($body['html']) && isset($body['text'])) {
                    // Both text and html have been passed, build extra multipart/alternative section
                    $bodystr .= "Content-Type: multipart/alternative; boundary=\"".($altboundary = "boundary-alt-$random_hash")."\"\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['text']."\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['html']."\r\n\r\n--$altboundary--\r\n\r\n--$mixedboundary";
                  } else if (($html = isset($body['html'])) || isset($body['text'])) {
                    // Only one of text or html have been passed, build as appropriate
                    $bodystr .= "Content-Type: text/".(($html) ? 'html' : 'plain')."; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".(($html) ? $body['html'] : $body['text'])."\r\n\r\n--$mixedboundary";
                  } else return FALSE;
                } else if (is_string($body)) {
                  // $body is a string, assume HTML 
                  $bodystr .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n$body\r\n\r\n--$mixedboundary";
                } else return FALSE;
                // Loop through attachments, base64 encode them and add them to $bodystr
                foreach ($attachments as $attachment => $type) if (is_file($attachment)) $bodystr .= "\r\nContent-Type: $type; name=\"".basename($attachment)."\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment\r\n\r\n".chunk_split(base64_encode(file_get_contents($attachment)))."\r\n--$mixedboundary";
                $bodystr .= "--";
                // Execute mail() and return the result
                return ($mailparams) ? @mail($to,$subject,$bodystr,$headerstr,$mailparams) : @mail($to,$subject,$bodystr,$headerstr);
              }
            
            ?>

              Dave,

              The below looks good and I've tried it, but its not embedding the item like it was before. It has the attachment which is great, looks like its attaching correctly, its just not doing the embed so when I open it in googlemail it shows at the top.

              Any thoughts?

              DaveRandom;10973011 wrote:

              Try this:

              <?php
              
                function sendIcalEmail ($firstname,$lastname,$email,$meeting_date,$meeting_name,$meeting_duration) { 
              
              $from_name = "My Name"; 
              $from_address = "myname@mydomain.com"; 
              $subject = "Meeting Booking"; //Doubles as email subject and meeting subject in calendar 
              $meeting_description = "Here is a brief description of my meeting\n\n"; 
              $meeting_location = "My Office"; //Where will your meeting take place 
              
              //Convert MYSQL datetime and construct iCal start, end and issue dates 
              $meetingstamp = strtotime($meeting_date . " UTC");     
              $dtstart= gmdate("Ymd\THis\Z",$meetingstamp); 
              $dtend= gmdate("Ymd\THis\Z",$meetingstamp+$meeting_duration); 
              $todaystamp = gmdate("Ymd\THis\Z"); 
              
              //Create unique identifier 
              $cal_uid = date('Ymd').'T'.date('His')."-".rand()."@mydomain.com"; 
              
              //Create Email Headers 
              $headers = array (
                "From" => "$from_name <$from_address>", 
                "Reply-To" => "$from_name <$from_address>", 
                "MIME-Version" => "1.0"
              );
              
              //Create Email Body (HTML) 
              $body = "<html>\r\n<body>\r\n<p>Dear $firstname $lastname,</p>\r\n<p>Here is my HTML Email / Used for Meeting Description</p>\r\n</body>\r\n</html>"; 
              
              //Create ICAL Content (Google rfc 2445 for details and examples of usage) 
              $ical = "BEGIN:VCALENDAR
              PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
              VERSION:2.0
              METHOD:PUBLISH
              BEGIN:VEVENT
              ORGANIZER:MAILTO:$from_address
              DTSTART:$dtstart
              DTEND:$dtend
              LOCATION:$meeting_location
              TRANSP:OPAQUE
              SEQUENCE:0
              UID:$cal_uid
              DTSTAMP:$todaystamp
              DESCRIPTION:$meeting_description
              SUMMARY:$subject
              PRIORITY:5
              CLASS:PUBLIC
              END:VEVENT
              END:VCALENDAR";    
              
              // Define data about the attachment
              $fileatt = 'dispatch.ics'; // Path to the file 
              $fileatt_type = "text/calendar"; // File Type 
              $attachments = array($fileatt => $fileatt_type);
              
              // write ICAL to file
              file_put_contents($fileatt,$ical);
              
              //SEND MAIL 
              return mail_attachments( $email, $subject, $body, $attachments, $headers ); 
              
                }
              
                function mail_attachments ($to, $subject, $body, $attachments, $headers = FALSE, $mailparams = FALSE) {
                  // Get random hash and define first boundary string
                  $mixedboundary = 'boundary-mixed-'.($random_hash = md5(time()));
                  // Validate $headers, unset the content-type if it is set and overwrite it with multipart/mixed
                  if (!$headers) $headers = array(); else foreach ($headers as $header => $data) if (strtolower($header) == 'content-type') unset($headers[$header]);
                  $headers['Content-Type'] = "multipart/mixed; boundary=\"$mixedboundary\"";
                  // Build extra headers into a string
                  $headersarr = array();
                  foreach ($headers as $header => $data) $headersarr[] = "$header: $data";
                  $headerstr = implode("\r\n",$headersarr);
                  // Start building body
                  $bodystr = "--$mixedboundary\r\n";
                  if (is_array($body)) {
                    if (isset($body['html']) && isset($body['text'])) {
                      // Both text and html have been passed, build extra multipart/alternative section
                      $bodystr .= "Content-Type: multipart/alternative; boundary=\"".($altboundary = "boundary-alt-$random_hash")."\"\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['text']."\r\n\r\n--$altboundary\r\nContent-Type: text/plain; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".$body['html']."\r\n\r\n--$altboundary--\r\n\r\n--$mixedboundary";
                    } else if (($html = isset($body['html'])) || isset($body['text'])) {
                      // Only one of text or html have been passed, build as appropriate
                      $bodystr .= "Content-Type: text/".(($html) ? 'html' : 'plain')."; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n".(($html) ? $body['html'] : $body['text'])."\r\n\r\n--$mixedboundary";
                    } else return FALSE;
                  } else if (is_string($body)) {
                    // $body is a string, assume HTML 
                    $bodystr .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\nContent-Transfer-Encoding: 7bit\r\n\r\n$body\r\n\r\n--$mixedboundary";
                  } else return FALSE;
                  // Loop through attachments, base64 encode them and add them to $bodystr
                  foreach ($attachments as $attachment => $type) if (is_file($attachment)) $bodystr .= "\r\nContent-Type: $type; name=\"".basename($attachment)."\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment\r\n\r\n".chunk_split(base64_encode(file_get_contents($attachment)))."\r\n--$mixedboundary";
                  $bodystr .= "--";
                  // Execute mail() and return the result
                  return ($mailparams) ? @mail($to,$subject,$bodystr,$headerstr,$mailparams) : @mail($to,$subject,$bodystr,$headerstr);
                }
              
              ?>
                richcranney;10973012 wrote:

                Dave,

                The below looks good and I've tried it, but its not embedding the item like it was before. It has the attachment which is great, looks like its attaching correctly, its just not doing the embed so when I open it in googlemail it shows at the top.

                Any thoughts?

                Dave,

                Ignore me, it works a treat. Just was my email not picking up the right version.

                Rich

                  Not a problem, glad to help 🙂

                  Mark this thread as resolved it your problem is sorted 😉

                    Dave,

                    Quick question. I'm still learning this code, but how do I delete the attachments from the local server once completed? I normally use unlink($attachment); but thats not working in this case.

                      The mail_attachments function reads the file from the disk, so you need to do it after you have sent the email.

                          //SEND MAIL 
                          return mail_attachments( $email, $subject, $body, $attachments, $headers );

                      ...wil become...

                          //SEND MAIL 
                          $mailresult = mail_attachments( $email, $subject, $body, $attachments, $headers );
                      
                      // Delete local file
                      unlink($fileatt);
                      
                      // Return result of sending email
                      return $mailresult;

                      If you always use the same file name, you don't actually need to bother - the next call of the function will overwrite the previous file - however in the interests of tidiness it's probably a good idea.

                        Your a genius! Now I just need to authenticate it via SMTP as it keeps going to my blooming spam lol.

                        Thanks for all the help

                        DaveRandom;10973019 wrote:

                        The mail_attachments function reads the file from the disk, so you need to do it after you have sent the email.

                            //SEND MAIL 
                            return mail_attachments( $email, $subject, $body, $attachments, $headers );

                        ...wil become...

                            //SEND MAIL 
                            $mailresult = mail_attachments( $email, $subject, $body, $attachments, $headers );
                        
                        // Delete local file
                        unlink($fileatt);
                        
                        // Return result of sending email
                        return $mailresult;
                          richcranney wrote:

                          Now I just need to authenticate it via SMTP

                          For that you really will have to use PEAR::Mail or something similar. PHP's native mail() function (and by extension, my mail_attachments() function) do not send via a legitimate server, they effectively look up the MX record for the destination address and send the mail directly to the server for the remote domain.

                          This will cause a lot of messages to get flagged as spam, as the reverse DNS of your web server does not match the domain of your From: address.

                          There are a few things you can do here:

                          1) If you're always sending to the same domain/set of domains, you can add an exception for your server in the spam filter(s) of the remote mail server(s)
                          2) If you are always using the same From: address, you can have your ISP set the reverse DNS of your server's IP so that it matches the domain of your From: address and/or default domain used in HELO/EHLO
                          3) You can relay your mail via a server which is set up correctly, either with an whitelist-based smarthost, or using SMTP auth

                          If you go for option 3 and need a hand with the code, let me know and I'll see what I can do... 🙂

                            I've just had a word with my host and I've had PEAR installed to the server, so looks like I can go down that route to get this authenticated.
                            You got any tips on converting this over as I notice I have to pass the email as ($to, $headers, $body), so missing the $subject.

                            I only ask as I have had problems with headers before, when I change them, the whole thing unravels. Email is so fiddly!

                            DaveRandom;10973021 wrote:

                            For that you really will have to use PEAR::Mail or something similar. PHP's native mail() function (and by extension, my mail_attachments() function) do not send via a legitimate server, they effectively look up the MX record for the destination address and send the mail directly to the server for the remote domain.

                            This will cause a lot of messages to get flagged as spam, as the reverse DNS of your web server does not match the domain of your From: address.

                            There are a few things you can do here:

                            1) If you're always sending to the same domain/set of domains, you can add an exception for your server in the spam filter(s) of the remote mail server(s)
                            2) If you are always using the same From: address, you can have your ISP set the reverse DNS of your server's IP so that it matches the domain of your From: address and/or default domain used in HELO/EHLO
                            3) You can relay your mail via a server which is set up correctly, either with an whitelist-based smarthost, or using SMTP auth

                            If you go for option 3 and need a hand with the code, let me know and I'll see what I can do... 🙂

                              It's a while since I've done this, let me just refresh myself...

                                Thanks,

                                I've managed to add the subject in here...

                                    //Create Email Headers 
                                    $headers = array ( 
                                      "From" => "$from_name <$from_address>", 
                                      "Reply-To" => "$from_name <$from_address>",
                                	  "Subject" => "$subject",
                                      "MIME-Version" => "1.0" 
                                    ); 
                                

                                Now the email comes through with headers absolutely perfect.

                                BUT, It still goes into my junk folder and when viewing the original email, I can see all sorts of Anti Abuse sections in there, they are these:

                                Delivered-To: richcranney@googlemail.com
                                Received: by 10.204.32.133 with SMTP id c5cs38089bkd;
                                        Sun, 23 Jan 2011 06:06:08 -0800 (PST)
                                Received: by 10.151.44.1 with SMTP id w1mr3294612ybj.253.1295791568233;
                                        Sun, 23 Jan 2011 06:06:08 -0800 (PST)
                                Return-Path: <test@richardcranney.com>
                                Received: from caesar.asmallorange.com (caesar.asmallorange.com [75.127.98.108])
                                        by mx.google.com with ESMTPS id u39si23472127yba.25.2011.01.23.06.06.07
                                        (version=TLSv1/SSLv3 cipher=RC4-MD5);
                                        Sun, 23 Jan 2011 06:06:08 -0800 (PST)
                                Received-SPF: neutral (google.com: 75.127.98.108 is neither permitted nor denied by best guess record for domain of test@richardcranney.com) client-ip=75.127.98.108;
                                Authentication-Results: mx.google.com; spf=neutral (google.com: 75.127.98.108 is neither permitted nor denied by best guess record for domain of test@richardcranney.com) smtp.mail=test@richardcranney.com
                                Date: Sun, 23 Jan 2011 06:06:08 -0800 (PST)
                                Message-Id: <4d3c35d0.2748960a.62d5.ffff80eeSMTPIN_ADDED@mx.google.com>
                                Received: from localhost ([127.0.0.1]:42123)
                                	by caesar.asmallorange.com with esmtpsa (TLSv1:AES256-SHA:256)
                                	(Exim 4.69)
                                	(envelope-from <test@richardcranney.com>)
                                	id 1Ph0Zz-00053V-88
                                	for richcranney@googlemail.com; Sun, 23 Jan 2011 09:06:07 -0500
                                From: Richard Cranney <test@richardcranney.com>
                                Reply-To: Richard Cranney <test@richardcranney.com>
                                Subject: Meeting Booking
                                MIME-Version: 1.0
                                Content-Type: multipart/mixed; boundary="boundary-mixed-49a9aa7a664a12f00dfbe50c94a66be9"
                                X-AntiAbuse: This header was added to track abuse, please include it with any abuse report
                                X-AntiAbuse: Primary Hostname - caesar.asmallorange.com
                                X-AntiAbuse: Original Domain - googlemail.com
                                X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12]
                                X-AntiAbuse: Sender Address Domain - richardcranney.com
                                X-Source: 
                                X-Source-Args: 
                                X-Source-Dir:
                                

                                I wonder if they are causing it to go into SPAM? I was thinking using the PEAR::mail option would remove them? Oh, just to let you know what I changed, I amended

                                return ($mailparams) ? @mail($to,$subject,$bodystr,$headerstr,$mailparams) : @mail($to,$subject,$bodystr,$headerstr);

                                to

                                // Now try with PEAR
                                	require_once "Mail.php";
                                	$host = "localhost";
                                	$username = "test@richardcranney.com";
                                	$password = "******";
                                
                                $smtp = Mail::factory('smtp',
                                array ('host' => $host,
                                'auth' => true,
                                'username' => $username,
                                'password' => $password));
                                
                                return ($mailparams) ? $smtp->send($to, $headers, $bodystr, $mailparams) : $smtp->send($to, $headers, $bodystr);
                                DaveRandom;10973024 wrote:

                                It's a while since I've done this, let me just refresh myself...

                                  Try this:

                                    require_once('Mail.php');
                                    require_once('Mail/mime.php');
                                  
                                    function sendIcalEmail ($firstname,$lastname,$email,$meeting_date,$meeting_name,$meeting_duration) { 
                                  
                                  // Data about the sender & email
                                  $from_name = "My Name"; 
                                  $from_address = "myname@mydomain.com"; 
                                  $subject = "Meeting Booking"; //Doubles as email subject and meeting subject in calendar 
                                  $meeting_description = "Here is a brief description of my meeting\n\n"; 
                                  $meeting_location = "My Office"; //Where will your meeting take place 
                                  
                                  // SMTP details
                                  $smtp_params = array (
                                    "host" => "smtp.myserver.com",
                                    "port" => 25,
                                    "auth" => TRUE,
                                    "username" => "user@myserver.com",
                                    "password" => "pass"
                                  );
                                  
                                  //Convert MYSQL datetime and construct iCal start, end and issue dates 
                                  $meetingstamp = strtotime($meeting_date . " UTC");     
                                  $dtstart= gmdate("Ymd\THis\Z",$meetingstamp); 
                                  $dtend= gmdate("Ymd\THis\Z",$meetingstamp+$meeting_duration); 
                                  $todaystamp = gmdate("Ymd\THis\Z"); 
                                  
                                  //Create unique identifier 
                                  $cal_uid = date('Ymd').'T'.date('His')."-".rand()."@mydomain.com"; 
                                  
                                  // Build sender/recipient in the form PEAR::Mail wants them
                                  $sender = "$from_name <$from_address>";
                                  $recipient = "$firstname $lastname <$email>";
                                  
                                  //Create Email Headers 
                                  $headers = array (
                                    'From' => $sender, 
                                    'Reply-To' => $sender, 
                                    'Return-Path' => $sender,
                                    'Subject' => $subject 
                                  );
                                  
                                  //Create Email Body (HTML) 
                                  $bodyhtml = "<html>\r\n<body>\r\n<p>Dear $firstname $lastname,</p>\r\n<p>Here is my HTML Email / Used for Meeting Description</p>\r\n</body>\r\n</html>"; 
                                  
                                  //Create ICAL Content (Google rfc 2445 for details and examples of usage) 
                                  $ical = "BEGIN:VCALENDAR
                                  PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
                                  VERSION:2.0
                                  METHOD:PUBLISH
                                  BEGIN:VEVENT
                                  ORGANIZER:MAILTO:$from_address
                                  DTSTART:$dtstart
                                  DTEND:$dtend
                                  LOCATION:$meeting_location
                                  TRANSP:OPAQUE
                                  SEQUENCE:0
                                  UID:$cal_uid
                                  DTSTAMP:$todaystamp
                                  DESCRIPTION:$meeting_description
                                  SUMMARY:$subject
                                  PRIORITY:5
                                  CLASS:PUBLIC
                                  END:VEVENT
                                  END:VCALENDAR";    
                                  
                                  // Create the Mime message object
                                  $mime = new Mail_mime("\r\n");
                                  
                                  // Add the HTML to the object
                                  $mime->setHTMLBody($bodyhtml);
                                  
                                  // Add the attachment
                                  $file_name = "dispatch.ics";
                                  $content_type = "text/calendar";
                                  $mime->addAttachment ($ical, $content_type, $file_name, 0);
                                  
                                  // Get the MIME message
                                  $body = $mime->get();
                                  $headers = $mime->headers($headers);
                                  
                                  // Create an SMTP object
                                  $mail =& Mail::factory("smtp", $smtp_params); 
                                  
                                  // Send the message
                                  return ($mail->send($recipient, $headers, $body) === 1) ? TRUE : FALSE;
                                  
                                    }
                                  • You will need ALL THREE of Mail, Mail_mime and Net_SMTP installed (you can do this with the command 'pear install <extension name>')

                                  • You will need to configure the details of your SMTP server at the top of the function

                                  • The attachment is no longer written to disk, so you don't need to worry about deleting it

                                  Not actually tested it so let me know how you get on...

                                    Hmm,

                                    I get the following error:

                                    Fatal error: Class 'Mail_mime' not found in /home/rcranney/public_html/testdomains/flex/mail_old3.php on line 132

                                    I've checked with my host and they assured me that the Mail_mime is included and sent me the log when they tried to re-install it:

                                    asojeff@caesar [~]# pear install Mail_mime
                                    pear/Mail_mime is already installed and is the same as the released version 1.8.1
                                    install failed

                                        require_once('Mail.php'); 
                                        require_once('Mail/mime.php');

                                      If you don't get any errors when you execute those, the classes should be available, but you have to include()/require() them in your script, in the global scope (preferably at the start of the script, not inside a function...)