I have customize mailer function where except file attachment, rest of things are working well. To make it simplify, I have added only code related to attachment. As output, I can see file uploaded to server but it's going to attach in email. I am getting all details in email except file attachment. it's customize mailer class which I have created but not sure why attachment not sending to email.
Mailer.class.php
<?php
class Mailer
{
private $addAttachment = [];
public function addAttachment($addAttachment)
{
if (empty($addAttachment))
{
$this->setError('No Attachments','empty');
}else{
$this->addAttachment[] = $addAttachment;
echo $addAttachment;
}
return $this;
}
}
For Sending test.php
require_once 'Mailer.class.php';
$toemails = array("my_email_address#gmail.com");
$toemail = implode(',', $toemails);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$attachment = $_FILES["uploaded_file"]["tmp_name"];
$folder = '/uploads/';
$file_name1 = $_FILES["uploaded_file"]["name"];
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "$folder".$_FILES["uploaded_file"]["name"]);
print_r($_FILES);
$mailer = new Mailer(true);
$mailer->setToEmail($toemail)
->setFromName(isset($_POST['fname'])?$_POST['fname']:'')
->setFromEmail(isset($_POST['email'])?$_POST['email']:'')
->setSubject('Application Regarding'.$_POST['Title'])
->addAttachment('/uploads/'.$_FILES["uploaded_file"]["name"])
->setBody($body)
->run();
exit();
if(!$mailer->sendMail()) {
echo "Something has gone wrong, please contact the site administrator or try again.";
}
else {
echo "Email Successfully Submitted";
}
print "</pre>";
}
?>
print_r($_FILES) gives me following Output for attachment:
Array
(
[uploaded_file] => Array
(
[name] => Image_Manager.pdf
[type] => application/pdf
[tmp_name] => /tmp/phplBV7gV
[error] => 0
[size] => 150300
)
)
Related
I'm working on editing a site which has been built using some strange Smarty system, template TPL files and a load of JS and PHP.
I have a Classes in PHP files which sends and email to an array of email address from a differnt PHP file.
I'm wanted to add to this array so it sends a copy of the email to the person who filled in the form.
The array of recipents is:
//target email address settings
$this->settings['mailer_address_booknow'] = array('ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'james#bernhardmedia.com');
And the sending PHP file is:
public function SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message ) {
$smartyObj = Configurator::getInstance()->smarty;
$send_message = '';
$send_result = 0;
try {
$mail = new PHPMailer( true );
$mail->IsSMTP( true );
$mail->SMTPDebug = false;
$mail->IsHTML( true );
$mail->Host = Configurator::getInstance()->getSettings( "phpmailer_smtp" );
$mail->ClearAddresses();
for( $x = 0;$x < sizeof($email_address_array);$x++ ){
$mail->AddAddress( trim($email_address_array[$x]) );
}
$smartyObj->assign( 'email_data', $email_data );
$mail->SetFrom( 'info#forexchange.co.uk', 'Forexchange Currency Order');
$mail->Subject = $subject;
$mail->Body = $smartyObj->fetch( $template );
if(!$mail->Send()) {
} else {
$send_result = 1;
}
} catch (phpmailerException $e) {
$send_message = $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$send_message = $e->getMessage(); //Boring error messages from anything else!
}
//echo $send_result;
//exit;
return $send_result;
}
The form is on the home page of this site - http://www.forexchange.co.uk/
Please help, I'm stumped!
Smarty I think refers to the Smarty template Engine for php see here
Append the email address to the array $email_address_array
When you call the method
SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message );
either append the email to that data set ($email_address_array) before you call it or append it inline ( in the call)
Can you show how you call it?
EDIT
If your data is stored in
$this->settings['mailer_address_booknow'];
add that to the call,
SendEmail( $this->settings['mailer_address_booknow'] , $email_data, $subject, $template, &$send_message );
if you need to add to that array then do this before calling it
$this->settings['mailer_address_booknow'] = "ADDED_EMAIL";
I am trying to send attachments with SendGrid through PHP, but keep getting a corrupted file error when I open the attachment. The error message "We're sorry. We can't open 'file.docx' because we found a problem with its contents" and when I click on the details of the error I see "The file is corrupt and cannot be opened"
My code looks like the below:
$sendGridLoginInfo = $contactViaEmail->getSendGridLoginInfo();
$sendgrid = new SendGrid($sendGridLoginInfo['Username'], $sendGridLoginInfo['Password']);
$mail = new SendGrid\Mail();
//Add the tracker args
$mail->addUniqueArgument("EmailID", $emailID);
$mail->addUniqueArgument("EmailGroupID", $emailGroupID);
/*
* INSERT THE SUBSITUTIONS FOR SEND GRID
*/
foreach ($availableSubstitutions as $availableSubstitution)
{
$mail->addSubstitution("[[" . $availableSubstitution . "]]", $substitutions[$availableSubstitution]);
}
/*
* ADD EACH EMAIL AS A NEW ADD TO
* This makes it BCC (because each person gets their own copy) and each person gets their own individualized email.
*/
foreach ($emailInfo['SendToEmailAddress'] as $toEmail)
{
if ($sendToLoggedInUser)
{
$mail->addTo($adminEmailAddress);
}
else
{
$mail->addTo($toEmail);
}
$trashCount++;
}
//Set the subject
$mail->setSubject($emailInfo['EmailSubject']);
//Instantiate the HTML Purifier (for removing the html)
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML', 'Allowed', '');
$purifier = new HTMLPurifier($config);
$mail->setText($purifier->purify($emailBody));
$mail->setHtml($emailBody);
if ($emailInfo['AttachmentID'])
{
$sql = "SELECT
AttachmentPath
FROM
EmailAttachments
WHERE
EmailAttachments.AttachmentID = :attachmentID";
if ($query = $pdoLink->prepare($sql))
{
$bindValues = array();
$bindValues[":attachmentID"] = $emailInfo['AttachmentID'];
if ($query->execute($bindValues))
{
if ($row = $query->fetch(\PDO::FETCH_ASSOC))
{
$attachment = "";
$mail->addAttachment($sitedb . $row['AttachmentPath']);
}
}
}
}
if ($sendToLoggedInUser)
{
$mail->setFrom($adminEmailAddress);
$mail->setReplyTo($adminEmailAddress);
}
else
{
$mail->setFrom($emailInfo['FromAddress']);
$mail->setReplyTo($emailInfo['ReplyTo']);
}
$mail->setFromName($emailInfo['FromName']);
$sendgrid->web->send($mail);
I've played with the content type and everything else that I can think of and just cannot find out what is causing the attachments to be corrupted.
You need to create an attachment object to add an attachment, you can't use the path directly like you are. SendGrid requires files to be sent as base64 encoded strings.
You'll need to create the attachment object, you could do this as a method:
public function getAttachment($path)
{
if (!file_exists($path)) {
return false;
}
$attachment = new SendGrid\Attachment;
$attachment->setContent(base64_encode(file_get_contents($path)));
$attachment->setType(mime_content_type($path));
$attachment->setFilename(basename($path));
$attachment->setDisposition('attachment');
return $attachment;
}
Then add it to your email:
$attachment = $this->getAttachment($sitedb . $row['AttachmentPath']);
if ($attachment instanceof SendGrid\Attachment) {
$mail->addAttachment($attachment);
}
I need send an email with attachments (words, pdf...) from a Contact form.
The email is sent well, but with .pdf not attached and with .docx I have a file without extension (choosing office to run it looks perfectly)
This is my code:
<form method="post" action="components/trabajamail.php" enctype="multipart/form-data">
<input type="file" name="userfile" accept="application/pdf,application/msword">
<button type="submit">Send</button>
My php file based on This:
$mail = new PHPMAILER ();
$mail->setFrom ( 'from#mail.com', 'Mailer' ); // Add a recipient
$mail->addAddress ( 'to#mail.com' );
$mail->isHTML ( true ); // Set email format to HTML
$mail->Subject = 'Subject';
$mail->Body = "Message";
$mail->CharSet = 'UTF-8';
// Attach the uploaded file
if (array_key_exists ( 'userfile', $_FILES )) {
$uploadfile = tempnam ( sys_get_temp_dir (), sha1 ( $_FILES ['userfile'] ['name'] ) );
if (move_uploaded_file ( $_FILES ['userfile'] ['tmp_name'], $uploadfile )) {
$mail->addAttachment ( $uploadfile, 'File' );
}
}
if (! $mail->send ()) {
echo "<div class='alert alert-warning'><strong>Error!</strong></div>";
} else {
echo "<div class='alert alert-success'><strong>Success!</strong></div>";
}
The last if never show me nothing, but i cant find the problem
I have read some threads with similar problems and I have used examples from the officinal page but I do not get this to work
I am new in wordpress. I am trying to send a mail with an attachment. But every time the mail is being sent but the attachment is not. I searched almost all the post related to this topic here but all the solutions failed for me. I checked the path a lot of times and found that it is correct from 'uploads' folder. Please help me. This is my code,
<?php
if(isset($_POST['email'])){
$to = $_POST['email'];
$pdf = $_POST['pdf'];
$subject = "Presidency Alumni Annual Report";
$message = "Please download the attachment.";
$headers = 'From: Presidency Alumni Association Calcutta <noreply#presidencyalumni.com>' . "\n";
if($pdf == 'a'){
$attachments = array(WP_CONTENT_DIR . 'uploads/2015/01/Coffee-Mug-Banner.jpg');
}
else if($pdf == 'b'){
$attachments = array(WP_CONTENT_DIR . 'uploads/2014/08/Alumni-Autumn-Annual-2014.pdf');
}
else{
$attachments = array(WP_CONTENT_DIR . 'uploads/2014/08/Autumn-Annual-2012.pdf');
}
wp_mail($to, $subject, $message, $headers, $attachments);
print '<script type="text/javascript">';
print 'alert("Your Mail has been sent successfully")';
print '</script>';
}
?>
The most probable reason this to happen is if the condition if($pdf == 'a') {...} else if ($pdf == 'b') {...}) is not true. Check to see if this variable pdf is set properly in your post HTML form.
Also make sure that the constant WP_CONTENT_DIR contains something, i.e. is not empty string, because otherwise your path to the attachments will be invalid, i.e. it is better to access your uploads directory like this:
<?php $upload_dir = wp_upload_dir(); ?>
The $upload_dir now contains something like the following (if successful):
Array (
[path] => C:\path\to\wordpress\wp-content\uploads\2010\05
[url] => http://example.com/wp-content/uploads/2010/05
[subdir] => /2010/05
[basedir] => C:\path\to\wordpress\wp-content\uploads
[baseurl] => http://example.com/wp-content/uploads
[error] =>
)
Then, modify your code:
$attachments = array($upload_dir['url'] . '/2014/08/Autumn-Annual-2012.pdf');
See the documentation.
I've never touched PHP, but was tasked with fixing an Intern's code..
I am trying to attach a file being uploaded to an email that I am sending. The email sends, but without the file. I am using PHPMailerAutoUpload.php (found on GitHub).
Here's the code I am using.
The attachment is being saved via move_uploaded_file
move_uploaded_file( $resume['tmp_name'] , $up_dir .basename( $random_var . '_wse_' . $resume['name'] ) )
Note: I have commented out the move_uploaded_file function to make sure I wasn't getting rid of the attachment.
require_once('phpmailer/PHPMailerAutoload.php');
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = false;
$mail->Host = 'oursmtp';
$mail->Port = 25;
$mail->setFrom( $_POST['E-mail'] , $_POST['first_name'] . " " . $_POST['last_name'] );
$mail->addAddress( 'test#test.com' );
$mail->Subject = "Test" . #date('M/D/Y');
$mail->msgHTML($msgDoc);
if (isset($_FILES['uploaded_file']) &&
$_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
$_FILES['uploaded_file']['name']);
}
if (!$mail->send()) {
$mailError = $mail->ErrorInfo;
$outcomeArr = array(
'outcome'=>'failure',
'message'=>'Error' . $mailError
);
echo json_encode( $outcomeArr );
exit();
} else {
// success
$outcomeArr = array(
'outcome'=>'success',
'message'=>'Thank you'
);
echo json_encode( $outcomeArr );
}
From what I have read, $_FILES is a temporary storage for uploaded files in PHP. With this code, the email sends, but with no attachment (only a link to the uploaded file location).
I tried following this, but it isn't working for me.
Your intern was apparently a rockstar that had no need to check for or indicate error conditions, and then mail will send even if there's no attachment or if there was an error during the upload. Change these bits to the code to tell you why the file wasn't attached:
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
if( ! $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'], $_FILES['uploaded_file']['name']) ) {
echo 'Error adding attachment: ' . $mail->ErrorInfo;
}
} else if( !isset($_FILES['uploaded_file']) ) {
echo 'No uploaded file found';
} else {
echo 'Uploaded file error: ' . $_FILES['uploaded_file']['error'];
}