How to send php exported Excel files as emails
Now we have realized the ability to download excel after clicking and send text emails. How can we combine the excel exported by php with the function of sending text emails? It is perfect to send the excel exported by php as an attachment.
1. generate an excel file:
Header ("Content-type: application/octet-stream ");
Header ("Accept-Ranges: bytes ");
Header ("Content-type: application/vnd. ms-excel ");
Header ("Content-Disposition: attachment; filename =". $ filename. ". xls ");
Header ("Pragma: no-cache ");
Header ("Expires: 0 ");
If (! Empty ($ title )){
Foreach ($ title as $ k =>$ v ){
$ Title [$ k] = iconv ("UTF-8", "GB2312", $ v );
}
$ Title = implode ("\ t", $ title );
Echo "$ title \ n ";
}
If (! Empty ($ data )){
Foreach ($ data as $ key => $ val ){
Foreach ($ val as $ ck => $ cv ){
$ Data [$ key] [$ ck] = iconv ("UTF-8", "GB2312", $ cv );
}
$ Data [$ key] = implode ("\ t", $ data [$ key]);
}
Echo implode ("\ n", $ data );
}
2. send an email:
Phpmailer class library
$ Mail = new PHPMailer ();
$ Mail-> CharSet = 'utf-8 ';
$ Mail-> IsSMTP ();
$ Mail-> SMTPAuth = true;
$ Mail-> SMTPSecure = '';
$ Mail-> Host = $ config ['smtp _ host']; // SMTP Server
$ Mail-> Port = $ config ['smtp _ port']; // The PORT number of the SMTP server
$ Mail-> Username = $ config ['smtp _ user']; // SMTP Server Username
$ Mail-> Password = $ config ['smtp _ pass']; // SMTP server Password
$ Mail-> SetFrom ($ config ['from _ EMAIL '], $ config ['from _ name']);
$ ReplyEmail = $ config ['reply _ e-mail ']? $ Config ['reply _ EMAIL ']: $ config ['from _ EMAIL'];
$ ReplyName = $ config ['reply _ name']? $ Config ['reply _ name']: $ config ['from _ name'];
$ Mail-> AddReplyTo ($ replyEmail, $ replyName );
$ Mail-> Subject = $ subject;
$ Mail-> MsgHTML ($ body );
$ Mail-> AddAddress ($ to, $ name );
If (is_file ($ attachment) {// Add an attachment
$ Mail-> AddAttachment ($ attachment );
}
Return $ mail-> Send ()
------ Solution --------------------
7th add row
Ob_start ();
Add after 23rd rows
$ S = ob_get_flush ();
File_put_contents ($ filename. ". xls", $ s );
$ Attachment = $ filename. ". xls ";
Execute email sending
------ Solution --------------------
There must be something wrong with you. Check it carefully.
You actually output a text file, which can be opened in notepad.
Functions and usage of ob functions are available in the manual
------ Solution --------------------
Khan! In this case, the exported file has no path. How do you send it as an attachment ??
Are you not a fantasy?
------ Solution --------------------
For more information, see:
Save the excel file on the server, obtain the excel file path, and then send it as an attachment by email. If you do not need this file, then you can delete it.