Sending an uploaded file as attachment but not saving to server - php

I have a contact form on my website that allows the user to send files as attachments to an email. Now my reasoning is that, I do not need or necessarily want every image to be uploaded to the website server, but when using the form input file I gets uploaded anyways.
It makes sense that the form uploads the file as this is its function but I would like to know if this is inevitable or if there is a way to still send the images as attachments but not have it uploaded to the server.

Pulled from this answer https://stackoverflow.com/a/23849972/ (and having spent some time to find them a solution).
Sidenote: I upvoted the answer it was pulled from, just so you know.
"I assigned $_FILES['attachment']['tmp_name'] to a temporary variable and it worked!
Dont know why but that solved it for me.
Here's my code"
// Swiftmail commands ====================================
require_once('./swiftmailer/lib/swift_required.php');
$transport = Swift_SmtpTransport::newInstance('smtp.host.com', 587)
->setUsername('email#host.com')
->setPassword('pass');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance()
->setSubject($subject_temp)
->setFrom(array($from_email => $full_name))
->setTo(array('email#host.com' => 'Jack'))
->setBody($message_temp)
->attach(Swift_Attachment::fromPath($file_temp_name)
->setFilename($name_of_file));
$result = $mailer->send($message);
// Swiftmail commands ====================================
Where $file_temp_name = $_FILES['attachment']['tmp_name']; and $name_of_file = basename($_FILES['attachment']['name']);
So in turn (and was something I knew could be done), you would be using the temporarily stored file on the server and attaching it to the mail, which automatically gets deleted once it has been successfully served/processed.

As stated in the comments:
1.) Even though it is possible to have the files automatically removed after posting, the email function I am using is not set up that way. Thus an upload to the server is inevitable. Or at least to my knowledge.
2.) I can delete the file from the server after sending the mail.
Will update if a solution is discovered that solves my problem the best.

Related

how to include php html file in PEAR mail

I have a php file that I use to send newsletters. Recently I moved to a new server and they use PEAR Mail instead of the default PHP mail to send mails and I had to update my script to function. But it's still not working. I get the TXT version not the HTML version.
If I manually enter the html codes inside the setHTMLBody() it works but when I replace it with my ob_start $output_string variable it doesn't work.
Here is my script;
ob_start();
include "URL/To/File.php";
$output_string = ob_get_contents();
ob_end_clean();
$headers['From'] = 'from#email.com';
$headers['Subject'] = 'Newsletter Subject';
require_once('Mail.php');
require_once('Mail/mime.php');
$message = new Mail_mime();
$message->setTXTBody("Your client doesn't support HTML.");
$message->setHTMLBody(''.$output_string.'');
$mail =& Mail::factory('mail');
$result = $mail->send('myemailaddress#gmail.com', $message->headers($headers), $message->get());
if (PEAR::isError($result)) {
echo("<span>" . $result->getMessage() . "</span>");
} else {
echo("<span style='color: #f7941c; font-weight: bold'>Congratulations!
Your mail has been sent successfully</span>");
}
how do I correctly input the line below correctly? It's not working as is right now.
$message->setHTMLBody(''.$output_string.'');
So I'm cold on this subject right now (working on mobile) though let's see if I can help you out. So I looked up the setHTMLBody function. It's a little fuzzy on the type that the expected parameters should be. In PHP you can get the type using gettype($example) (like console.log(typeof example); in JavaScript though PHP is generally more forgiving about types (calculating a number that has a string type will work in PHP, not JavaScript)).
The name of the function implies that it should make this part of the email HTML. Now of all the modules I've built on my web platform email has been the most challenging not because it's inherently complex though because it's very subjective. In example some servers might expect you to serve an <html> element, others a <body> element and others won't care if you omit it (and I'm not sure what if any specifications declare what is "proper" here). I've not intentionally worked with compressing data in emails (just output in web mail though it's technical context is lost at that point). Long story straight here: the client's user agent (browser, email application, etc) should be handling the compression, not you.
PHP ob stuff is a bit convoluted. I dislike the same function/method being used for both compression and being able to capture and do find/replace with the output before sending it to a client. I think you're using it for compression though you could also be using it to replace bits of code for whatever reason. In this case your best bet for troubleshooting (presuming that your ob should work, most likely for replacing bits of code) is to use the string and test it outside of this environment. When I test cron jobs I always test them in normal environments first (though keep in mind cron jobs run in a much more limited environment so for debugging there I just have print_r($_SERVER) send me information via email).
So I think your ob code is messing up the parser setHTMLBody() function. Break your code down until you have working bits and then add your necessary and increasingly complex bits to it until you hit a problem and then because you know exactly what you just added you'll be able to single out the issue much easier.
I'd need further clarification though I can edit this answer later. Let me know where you're at, I always check notifications even if it takes a day.
I have a few dozen tools that I use when I develop. I'm not sure if this tool will validate though it may help you somehow since you are working on email. https://www.mail-tester.com/ helped me address some issues related to email (it's not related to this issue).

How to self-send an email with XAMPP-Mercury Mail using php

I've been searching a lot, but can't really find what i exactly need.
Im running a shop-online using XAMPP, and what i want is send emails to the customers with their order but using a specific function.
What this fuction does, is to hide some characters (for security purpose) on the email sent to customers. So i've made the function (looking on internet), but i want to test it now.
This is my function (if it's wrong, i'd really appreciate some help):
<?php
function xtc_hide_iban ($iban) {
$length = strlen($iban);
$lchars = substr($iban,0 ,5);
$rchars = substr($iban, -5);
$iban_hidden = $lchars.str_repeat('*',$length-10).$rchars;
return $iban_hidden;
}
?>
I think it's pretty obvious what i try to do, but i will still explain it:
Get the $iban from customers, and show only the first and last 5
characters when the email is sent e.G
Your IBAN is 'DE123************56789'
So, for now i can send emails from Mercury mail server to 'root#localhost',account i made on thunderbird, (it's the only account that worked for me, because any other with the same server, like 'anyname#localhost' didn't work or couldn't be created, and those who were create with imap before couldn't access to the inbox "could not connected to server, connection refuse", anyway this works with POP3)
Following what i looked before, is that somehow and somewhere i can put a *.php on Mercury folder so i will get a template of how to send the mails (headers, subject,body,etc).
My main question is how and where to do that? make a test php file to make sure my code is doing what i want to do
Thanks in advance

Parse email sent from Outlook piped to php

Using this tut: parse emails
I was able to get email piping, and attachment/body parsing totally working....as long as the email is not sent from outlook.
It executes perfectly from gmail, and thunderbird, however when the incoming email is sent from outlook the script fails. I figure it has something to do with how outlook formats its messages (in the comments on the tutorial site someone mentions outlook not being compliant), but truthfully the issue is above my head. Any help would be appreciated, thanks.
fyi: this is the newest version of outlook (win7).
As you have encountered, Outlook is the scourge of the email universe. You'll notice that the source provided in the tutorial you're using refers several times to content encoded as text/plain. The email being sent from Outlook likely contains text/html content instead of or in addition to the plaintext.
Depending on what you wish to do with the content of the email, you may be able to adapt the script to accept text/html encoded content as well by inserting a duplicate body search below the existing one like so:
//get the message body
if(substr($decoded[0]['Headers']['content-type:'],0,strlen('text/html')) == 'text/html' && isset($decoded[0]['Body'])){
$body = $decoded[0]['Body'];
} elseif(substr($decoded[0]['Parts'][0]['Headers']['content-type:'],0,strlen('text/html')) == 'text/html' && isset($decoded[0]['Parts'][0]['Body'])) {
$body = $decoded[0]['Parts'][0]['Body'];
} elseif(substr($decoded[0]['Parts'][0]['Parts'][0]['Headers']['content-type:'],0,strlen('text/html')) == 'text/html' && isset($decoded[0]['Parts'][0]['Parts'][0]['Body'])) {
$body = $decoded[0]['Parts'][0]['Parts'][0]['Body'];
}
Which certainly isn't pretty, but should retrieve the HTML content coming from Outlook if it is detected.
If you need to actually parse the HTML content, your problem will be a bit more complicated. Your next step would be to take a look at some of the answers for this question: Robust, Mature HTML Parser for PHP.
Good luck!
Ok...
So I fixed it. I was setting up the pipe in Cpanel, because it's easier. I put the pipe under "account level filtering", worked great for anything but outlook. I would have loved to have the script print data for debug, but it was never even executing when the email came from outlook. Looked in mail logs...nothing obvious. My admin on a whim suggested that I move the pipe to the "forwarders" section in cpanel. Well now it works perfect. Must be a bug in cpanel. Why is it the more you learn about computers the less sense they make.
Just a couple other tweaks I had to implement:
A) when writing/editing the script in a windows environment, hidden characters are added. To fix this, I upload the php file, and open it in the cpanel filemanager (us-ascii), and save it. This removes the characters. (could obviously open in *nix also)
B) I had to chmod to 755, or it would not run. Scripts sitting outside my \www so no worries.
C) My shebang had to be: #!/usr/bin/php -q. The q was necessary to get it running.
Hope this helps someone else.

Spam check before sending using Zend_Mail

I'm using Zend_Mail and the following code to send my email messages.
$mail = new Zend_Mail('UTF-8');
$mail ->setBodyText($plainBody)
->setBodyHtml($htmlBody)
->setSubject($subject)
->setFrom(FROM_ADDR, FROM_NAME)
->addTo($email, $name )
->addHeader(MY_HEADER, serialize( array( 'foo' => 'bar' ) ) )
;
I need to check the spam rating for the prepared message and I'd like to do it using SpamAssassin.
I thought to create a file with the contents and running something such as exec('spamc $filename'), but how to get the file content with the full MIME body?
I noticed that there's a _buildBody() function in Zend_Mail_Abstract class (library/Zend/Mail/Transport/Abstract.php) that's return that, but that's a protected function.
Thanks
If you want to use SpamAssasin, then run your email message through spamc:
http://spamassassin.apache.org/full/3.1.x/doc/spamc.html
Spamc is the client half of the spamc/spamd pair. It should be used in
place of spamassassin in scripts to process mail. It will read the
mail from STDIN, and spool it to its connection to spamd, then read
the result back and print it to STDOUT. Spamc has extremely low
overhead in loading, so it should be much faster to load than the
whole spamassassin program.
You can do use in PHP by:
Writing the message into a temporary file and running shell_exec('spamc < message.tmp'), or
Running the command with proc_open() then send message via STDIN.
I am assuming you want to simulate a spam check on the recipient's end. That's an interesting idea, but note that the results it will give you will be far from 100% realistic. After all, it's the sending process that adds much of the vital information that helps determine whether an E-Mail is spam (e.g. the sender IP and routes.)
Anyway, to do this, you will probably have to implement a custom Zend_Mail_Transport class, based on the example of Zend_Mail_Transport_Smtp. Any data that transport class sends to the SMTP server, you would have to re-route to a text file. As far as I can see at a cursory glance, it's going to be a bit of work but not impossible.

how to send image in newsletter?

can anyone tell me how can i send images as main body part in newsletter. how can i add any image from backend such that when i send a newsletter to the subscribers the image i want to show goes as main body part of the mail.
actually what i am saying is i have a form in which i can enter text and that text goes well in newsletter. now i want to add images in the form as well so that i don't need to write anything and only image will go in the mail as main body part of mail.
Thank you so much.
you guys have been very supportive to me.
If your newsletter is in HTML format, simply link to the live images that are on a server.
If you don't have your own server, simply host the images in any sort of free images hosting i.e. (imageshack.us) and on the body of your emails add:
<img src="http://imageshack.us/myimage.png">
And when the user opens the email, the images will load from the server.
As long as the email is multi-part (as previously suggested), any users that "can't read" HTML, will get the text version, which can have "hard-links" to the images on your live server.
Hope this helps you
First, you need to send your newsletter as HTML. Then, you can insert the image in your newsletter as
<img src="image_url">
The image_url can be remote or embedded. The remote image makes email smaller but most mail clients will ask user's approval. The embedded image will be displayed without asking user but it will be part of Email.
To use remote image, just host the image somewhere and put the URL as image_url.
Embedded image needs to be encoded as MIME parts. It's not trivial to do this. You need to use a package like PhpMailer,
http://sourceforge.net/projects/phpmailer/
Here is an example,
<?php
require("class.phpmailer-lite.php");
$mail = new PHPMailerLite();
$mail->From="you#example.com";
$mail->FromName="Your Name";
$mail->AddAddress("list#example.com");
$mail->Subject = "Your fancy newsletter";
$mail->IsHTML(true);
$mail->AddEmbeddedImage('image.png', 'image_id', 'test.png', 'base64', 'image/png');
$mail->Body = <<<EOT
<h1>My Newsletter</h1>
<p>This picture is embedded in newsletter: <img src="cid:image_id" /></p>
EOT;
$mail->AltBody="Text only, sorry no image";
if(!$mail->Send())
{
echo "Error sending: " . $mail->ErrorInfo;
}
else
{
echo "Mail is sent";
}
?>
You should create a multipart mime message, containing the image and maybe some HTML.
I wouldn't recommend attaching images to an email....it's one of many flags to email service providers that you're sending spam. Best to do as listed in Marcos' solution and link from another server via absolute URL. Remember also to avoid the obvious email no-nos that will get you black flagged. It only takes one questionable email to raise a flag with a spam filter that will aggressively report you to the RBL's. And trust me, it's not fun to get off those lists!
My company sends tens of thousands of emails on behalf of our clients every day. We tried embedding at one point for a test, and found that more than 50% of our emails were either undeliverable or lost in the "great abyss" of spam filtering. By linking, we're at well over 85% deliverablility, depending of course on the quality of the emails provided.

Categories