I need to attach a file to an outbound email automatically...Help - php

I have one form (input.html) that's completed by people working in five different divisions of this business. When the form is submitted it posts to output.php.
Output.php does a number of things:
First it displays all of the input information to the screen as a completed form. (Just to show them their completed document).
It has also created a file called unique_file.html based on two of the input fields in input.html.
Next, output.php has sent an email to one of five email groups, based upon another input field selected in input.html.
Finally (for now), I need the unique_file.html to be an attachment to the email. That is my problem.
I have found scripts for uploading files, I have found many tutorials about uploading files, but I just want to attach the unique_file.html to my outgoing email and I am not seeing how that is done.
Can someone point me in the right direction as to where to start? I am certainly missing the boat on this one and I have probably seen it and not realized it.

If you can use the Zend_Framework you can easily attach file to an email i.e.
$mail = new Zend_Mail();
$at = new Zend_Mime_Part($myImage);
$at->type = 'image/gif';
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
$at->encoding = Zend_Mime::ENCODING_8BIT;
$at->filename = 'test.gif';
$mail->addAttachment($at);
$mail->send();
see the documentation,
You should be able to attach a file also by using Mail_Mime pear package and the normal mail function.
But I think the solution using the Zend framework is much more straight forward.
Cheers.

I find PHPMailer best for this. An example from their site:
require_once('../class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}

Related

Problems With Emailing Through A Submit Button

After going through my website the user can email me a file and a brief description to go along with it. However once the user of my website clicks the submit button, he goes to a page that says "this webpage is unavailable" and I don't get an email.
I have been using PHP and HTML for this part of my website and I don't know why it isn't working.
PHP
<?php
mail('Example#gmail.com', $_POST['Subject'], $_POST['Content']);
?>
HTML
<form method="post" action="email.php">
<input type="file">
<input type="text">
Content Goes Here
<br>
<br>
<input type="Submit">
</form>
Try to use something like libmail class for sending Emails, in most cases it fixes the problem.
If even after making it work with libmail you will get an issues, try to use SMTP along with libmail.
Cheers.
Sure, here is example of usage:
Download php_libmail class with this link http://webi.ru/base/files/tovar/php_libmail_2_1.zip
Then use this code:
<?php
include "libmail.php"; // including the class
$m= new Mail; // create instance
$m->From( "asd#asd.com" ); // from
$m->To( "who#asad.com" ); // to
$m->Subject( "Subject zzz" ); // subject
$m->Body( "Hey, pal" ); // body
$m->Cc( "copy#asd.com"); // copy of email, if need
$m->Bcc( "bcopy#asd.com"); // hidden copy of email, if need
$m->Priority(3) ; // priority of message, i think from 1 to 5
$m->Attach( "asd.gif","", "image/gif" ) ; // attachment, if need
$m->smtp_on( "smtp.asd.com", "login", "password" ) ; // via SMTP, if need
$m->Send(); // And the magic Send ;)
echo "Message body:<br><pre>", $m->Get(), "</pre>";
?>
For make functionality you need, just create simple HTML form with enctype="multipart/form-data" attribute and add any fields you want, files, inputs, texts, any of those.
And then in you PHP script accept those field values via global $_POST variable and pass accepted values into the libmail instance ;)
For accepted files use global $_FILES variable.
You can simply use PHP Mailer for sending any mail.
It is very helpful and easy way to do this kind of work.
Code would be like-
<?php
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "from#yourdomain.com";
$mail->FromName = "Full Name";
//To address and name
$mail->addAddress("recepient1#example.com", "Recepient Name");
$mail->addAddress("recepient1#example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("reply#yourdomain.com", "Reply");
//CC and BCC
$mail->addCC("cc#example.com");
$mail->addBCC("bcc#example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
Here is a illustrative example given for this.

send email using gmail-api and google-api-php-client

I am using https://github.com/google/google-api-php-client and I want to send a test email with a user's authorized gmail account.
This is what I have so far:
$msg = new Google_Service_Gmail_Message();
$msg->setRaw('gp1');
$service->users_messages->send('me', $msg);
This results in a bounce email because I have no clue how to set the raw message. I see the bounce in the inbox of my authenticated user. I want to learn how to set values for 'To', 'Cc', 'Bcc', 'Subject', and 'Body' of the email. I believe I will need to do a 64 encoding on that raw data as well. And I might want to use some html in the body of my email.
Please help to provide a working example of sending an email using the gmail-api and the google-api-php-client.
Here is the bounced email in the inbox:
Bounce -nobody#gmail.com- 12:58 PM (7 minutes ago)
to me
An error occurred. Your message was not sent.
‚ Date: Thu, 24 Jul 2014 10:58:30 -0700 Message-Id: CABbXiyXhRBzzuaY82i9iODEiwxEJWO1=jCcDM_TH-
I asked a more specific question which has led me to an answer. I am now using PHPMailer to build the message. I then extract the raw message from the PHPMailer object. Example:
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$subject = "my subject";
$msg = "hey there!";
$from = "myemail#gmail.com";
$fname = "my name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress("tosomeone#somedomain.com");
$mail->AddReplyTo($from,$fname);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);
I've used this solution as well, worked fine with a few tweaks:
When creating the PHPMailer object, the default encoding is set to '8bit'.
So I had to overrule that with:
$mail->Encoding = 'base64';
The other thing i had to do was tweaking the MIME a little to make it POST ready for the Google API, I've used the solution by ewein:
Invalid value for ByteString error when calling gmail send API with base64 encoded < or >
Anyway, this is how I've solved your problem:
//prepare the mail with PHPMailer
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
//supply with your header info, body etc...
$mail->Subject = "You've got mail!";
...
//create the MIME Message
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
//create the Gmail Message
$message = new Google_Service_Gmail_Message();
$message->setRaw($mime);
$message = $service->users_messages->send('me',$message);
Perhaps this is a bit beyond the original question, but at least in my case that "test email" progressed to regularly sending automated welcome emails "from" various accounts. Though I've found much that is helpful here, I've had to cobble things together from various sources.
In the hope of helping others navigate this process, here's a distilled version of what I came up with.
A few notes on the following code:
This assumes that you've jumped through the hoops to create and download the JSON for a Google Service Account (under credentials in the developer dashboard it's the bottom section.)
For clarity, I've grouped all the bits you should need to set in the "Replace this with your own data" section.
That me in the send() method is a key word that means something like "send this email with the current account."
// This block is only needed if you're working outside the global namespace
use \Google_Client as Google_Client;
use \Google_Service_Gmail as Google_Service_Gmail;
use \Google_Service_Gmail_Message as Google_Service_Gmail_Message;
// Prep things for PHPMailer
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
// Grab the needed files
require_once 'path/to/google-api/vendor/autoload.php';
require_once 'path/to/php-mailer/Exception.php';
require_once 'path/to/php-mailer/PHPMailer.php';
// Replace this with your own data
$pathToServiceAccountCredentialsJSON = "/path/to/service/account/credentials.json";
$emailUser = "sender#yourdomain.com"; // the user who is "sending" the email...
$emailUserName = "Sending User's Name"; // ... and their name
$emailSubjectLine = "My Email's Subject Line";
$recipientEmail = "recipient#somdomain.com";
$recipientName = "Recipient's Name";
$bodyHTML = "<p>Paragraph one.</p><p>Paragraph two!</p>";
$bodyText = "Paragraph one.\n\nParagraph two!";
// Set up credentials and client
putenv("GOOGLE_APPLICATION_CREDENTIALS={$pathToServiceAccountCredentialsJSON}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
// We're only sending, so this works fine
$client->addScope(Google_Service_Gmail::GMAIL_SEND);
// Set the user we're going to pretend to be (Subject is confusing here as an email also has a "Subject"
$client->setSubject($emailUser);
// Set up the service
$mailService = new Google_Service_Gmail($client);
// We'll use PHPMailer to build the raw email (since Google's API doesn't do that) so prep it
$mailBuilder = new PHPMailer();
$mailBuilder->CharSet = "UTF-8";
$mailBuilder->Encoding = "base64";
// Not set up the email you want to send
$mailBuilder->Subject = $emailSubjectLine;
$mailBuilder->From = $emailUser;
$mailBuilder->FromName = $emailUserName;
try {
$mailBuilder->addAddress($recipientEmail, $recipientName);
} catch (Exception $e) {
// Handle any problems adding the email address here
}
// Add additional recipients, CC, BCC, ReplyTo, if desired
// Then add the main body of the email...
$mailBuilder->isHTML(true);
$mailBuilder->Body = $bodyHTML;
$mailBuilder->AltBody = $bodyText;
// Prep things so we have a nice, raw message ready to send via Google's API
try {
$mailBuilder->preSend();
$rawMessage = base64_encode($mailBuilder->getSentMIMEMessage());
$rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); // url safe
$gMessage = new Google_Service_Gmail_Message();
$gMessage->setRaw($rawMessage);
// Send it!
$result = $mailService->users_messages->send('me', $gMessage);
} catch (Exception $e) {
// Handle any problems building or sending the email here
}
if ($result->labelIds[0] == "SENT") echo "Message sent!";
else echo "Something went wrong...";
Create the mail with phpmailer works fine for me in a local enviroment. On production I get this error:
Invalid value for ByteString
To solve this, remove the line:
$mail->Encoding = 'base64';
because the mail is two times encoded.
Also, on other questions/issues I found the next:
use
strtr(base64_encode($val), '+/=', '-_*')
instead of
strtr(base64_encode($val), '+/=', '-_,')
I Used https://developers.google.com/gmail/api/v1/reference/users/messages/send
and able to send email successfully.

Send a file through email after Paypal payment is recieved

Is there any way to send a file in an email upon receiving a Paypal payment? Any tutorials to show how to do this? Any help would be much appreciated.
I would use SwiftMailer / attahching files if I were you upon receiving confirmation from PayPal.
Sending email is easy using the built in mail function in PHP. However, sending attachment is a whole other story.
I'd use a third party library like phpMailer
E.g. sending email with attachment:
require_once('path/to/class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$address = "whoto#otherdomain.com";
$mail->AddAddress($address, "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}

Script php : send mail using phpmailer

I'm trying to send a simple email using phpmailer.
I really have no idea if it's relevant since I'm just doing a php script, but I have apache2 & sendmail, apache2 running and sendmail include in the php.ini (sendmail_path=etc).
So here is my code :
<?php
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "<h1>Coucou</h1>";
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo("totest#test.com","First Last");
$mail->SetFrom('fromtest#test.com', 'First Last');
$mail->AddReplyTo("totest2#test.com","First Last");
$address = "XXXX#gmail.com";
$mail->AddAddress($address, "XXXXX");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
//$mail->AddAttachment("./test.doc"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
So the thing is that my output is always "Message sent!", even if the script take a really long time to be executed (up to 10minutes !), but the mail never arrived to my mailbox (and I checked the spam folder).
Well I hope someone will have an explanation to that annoying problem!
Thank you anyway.
Regards,
Bdloul

PHPMailer With Attachment Never Received

I am tying to send an email with an attachment using phpmailer.
include_once('/home/site/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$body = $mail->getFile('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "smtp.free.fr"; // SMTP server
$mail->IsSendmail(); // telling the class to use SendMail transport
$mail->From = "name#sub.fr";
$mail->FromName = "name";
$mail->Subject = "subject";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress("sub#sub.net", "name");
$mail->AddAttachment("mylist.csv"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I receive a "Message sent !" on execution, but no email is ever received.
It is very possible the user you sent the email to did not recieve it due to the fact a lot of mail providers such as AOL and Yahoo block massive amounts of Ip addresses related to email spam. So if the server you are running this php script from is on their blacklist the user will not even receive it to the spam folder.
Check your php email logs.
http://help.yahoo.com/l/us/yahoo/smallbusiness/webhosting/php/php-03.html
Also, if this is not the case, try making sure the file your trying to include exists, and you are passing the correct path to the file. Like #Waygood said, try seeing if it sends without the attachment.

Categories