Trouble getting file attachment to work with Swiftmailer - php

I am trying to use swiftmailer to upload a file from a form, but I still get an error.
I really don't know where I'm going wrong. Any help and explanation would be greatly appreciated.
index.html
<form method="post" action="mail.php" enctype="multipart/form-data">
Attach a file: <input type="file" id="attachment" name="attachment">
<button type="submit">SUBMIT</button>
</form>
mail.php (correct)
Then it imports mail_sender.php
mail_sender.php
<?php
$file = 'attachment/'.basename($_FILES['attachment']['name']);
$upload = move_uploaded_file($_FILES['attachment']['tmp_name'],$file);
if(isset($timeZone) && $timeZone != ""){
date_default_timezone_set($timeZone);
}
else{
date_default_timezone_set("UTC");
}
// Require the Swift Mailer library
require_once 'swift_required.php';
$messageText = "";
if($emailMethod == 'phpmail'){
$transport = Swift_MailTransport::newInstance();
}elseif($emailMethod == 'smtp'){
$transport = Swift_SmtpTransport::newInstance( $outgoingServerAddress, $outgoingServerPort, $outgoingServerSecurity )
->setUsername( $sendingAccountUsername )
->setPassword( $sendingAccountPassword );
}
$mailer = Swift_Mailer::newInstance($transport);
// Creating the message text using fields sent through POST
foreach ($_POST as $key => $value)
{
// Sets of checkboxes will be shown as comma-separated values as they are passed in as an array.
if(is_array($value)){
$value = implode(', ' , $value);
}
$messageText .= ucfirst($key).": ".$value."\n\n";
}
if(isset($_POST['email']) && isset($_POST['name']) ){
$fromArray = array($_POST['email'] => $_POST['name']);
}else{ $fromArray = array($sendingAccountUsername => $websiteName); }
$message = Swift_Message::newInstance($emailSubject)
->setFrom($fromArray)
->addPart(strip_tags($messageText), 'application/pdf')
->attach(Swift_Attachment::fromPath($file))
->setTo(array($recipientEmail => $recipientName))->setBody($messageText, 'text/html');
}
// Send the message or catch an error if it occurs.
try{
echo($mailer->send($message));
}
catch(Exception $e){
echo($e->getMessage());
}
exit;
?>
Thanks in advance

Related

File attachments fails

Hi I am trying to send a mail with phpmailer lib, with option to attach multiple files.
But my mailer script doesnt send mails.
I have used a similar script to send mails successfully. But it fails when I try with attachments. I followed the PHPmailer example.
(I am using recaptcha 3 with this form.)
If possible, kindly take a look and let me know what I might be doing wrong.
Thanks a lot in advance.
The html file
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Multiple File Upload</title>
</head>
<body>
<form method="post" id="contact-form" enctype="multipart/form-data" action="testmailer.php">
<input name="fname" placeholder="Your name" title="Your name" type="text" /></div>
Select one or more files:
<input name="userfile[]" type="file" multiple="multiple">
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
<input type="submit" id="submit-button" value="Send Files">
<div id="alertm"></div>
</form>
<script>
$('#contact-form').submit(function(event) {
event.preventDefault();
$('#alertm').text('Processing...').fadeIn(0);
grecaptcha.ready(function () {
grecaptcha.execute('xxxrecaptcha3-site_keyxxx', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
// Make the Ajax call here
$.ajax({
url: 'testmailer.php',
type: 'post',
data: $('#contact-form').serialize(),
dataType: 'json',
success: function( _response ){
// The Ajax request is a success. _response is a JSON object
var error = _response.error;
var success = _response.success;
if(error != "") {
// In case of error, display it to user
$('#alertm').html(error);
}
else {
// In case of success, display it to user and remove the submit button
$('#alertm').html(success);
$('#submit-button').remove();
}
},
error: function(jqXhr, json, errorThrown){
// In case of Ajax error too, display the result
var error = jqXhr.responseText;
$('#alertm').html(error);
}
});
});
});
});
</script>
</body>
</html>
The mail sending script
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/PHPMailer/src/PHPMailer.php';
use PHPMailer\PHPMailer\PHPMailer;
$mail = new PHPMailer();
if(isset($_POST['fname'])){
$name=$_POST['fname'];
}
function isValid() {
if($_POST['name'] != "") {
return true;
} else {
return false;
}
}
$email_to = "email#domain.com";
$mail->setFrom('no-reply#somedomain.com', 'SomeDomain Mailer');
$mail->Subject = 'File Attachment';
$body = "Name - $name\n";
$mail->Body = $body;
if (array_key_exists('userfile', $_FILES)) {
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
if (!$mail->addAttachment($uploadfile, $filename)) {
$msg .= 'Failed to attach file ' . $filename;
}
} else {
$body .= 'Failed to move file to ' . $uploadfile;
}
}
$mail->IsHTML(true);
$error_output = '';
$success_output = '';
if(isValid()) {
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = '***recaptcha3-secret_key***';
$recaptcha_response = $_POST['recaptcha_response'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == 'contact') {
$mail->send();
$success_output = "Your message sent successfully";
} else {
$error_output = "Something went wrong. Please try again later";
}
} else {
$error_output = "Please fill all the required fields";
}
$output = array(
'error' => $error_output,
'success' => $success_output
);
// Output needs to be in JSON format
echo json_encode($output);
}
?>

Can't attach files from form using phpMailer

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

PHP Page is not Sending Email

I have a page that has a form for the user to input their email into. Once the form is submitted the email gets checked in my MSSQL table and if it exists in one of the table's rows it will send an email to the user's email. Right now, I correctly put in an existing email and the email is never received. I am trying to make this so that if the user forgets their password, it will retrieve the password from the correct row and send that password to the user's email.
Here is my PHP page code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$conn=mssql_connect('gdm','dr','Rd1!');
mssql_select_db('Gdr',$conn);
if (isset($_POST['forgotpass'])) {
$conn=mssql_connect('gdom','GBdr','d1!');
mssql_select_db('Gdr',$conn);
if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$email = $_POST['email'];
$querye = "SELECT password FROM staffportal WHERE email = '".$_POST['email']."'";
$check = mssql_query($querye, $conn);
$check2 = mssql_num_rows($check);
echo "".$check2."";
//if the email doesn't exist it gives an error
if ($check2 != 0) {
print"<p>Thank you, dsa we will get back to you.</p>";
print"<p>Today's date isdsa.</p>";
ob_start();
$tae = "".$_POST['email']."";
echo "".$tae."";
$out2 = ob_get_contents();
ob_end_clean();
var_dump($out2);
var_dump($out2);
$to = "".$out2."";
echo "Emailing to: ".$to."";
$subject = "Financing fordsac ";
$body = "dsdasd \n\n";
$headers = "From: info#gbmtd.ca";
mail($to, $subject, $body, $headers);
} else {
echo "Sorry, the email ".$email." is incorrect.";
} } else {
?>
<form method="POST" action="<?php $_PHP_SELF ?>">
Email:<br />
<input type="text" name="email" id="email"/>
<br /><br />
<input type="submit" id="forgotpass" value="Change Password" name="forgotpass"/>
</form>
<?php } ?>
</body>
</html>
This gets displayed on my page after I hit submit:
1
Thank you, dsa we will get back to you.
Today's date isdsa.
string(22) "kelseynealon#gmail.com" string(22) "kelseynealon#gmail.com" Emailing to: kelseynealon#gmail.com
All help is greatly appreciated. Thank you for any help.
I've had mixed luck with the PHP mail function. You can take a gander at the PHP mail function page http://www.php.net/manual/en/function.mail.php to look for clues. Personally I use PHP SwiftMailer (http://swiftmailer.org/) for any email sending from PHP applications and it works really well.
Here's a generic function I have for using it:
/*
Starting code for sending email via this function:
list($email_logger, $email_mailer) = email_interface();
$message = Swift_Message::newInstance()
->setFrom(array('from#domain.ext' => 'John Doe'))
->setTo(array('to#domain.ext' => 'Jane Doe'))
->setSubject('<SUBJECT>')
->setBody('<BODY>');
$email_mailer->send($message);
*/
// Returns PHP SwiftMailer mailer and logger email interfaces
function email_interface()
{
// Mail configuration
$global_email_config = array(
//'relay_encryption' => 'ssl',
//'relay_host' => 'relayhost.domain.ext',
//'relay_port' => '465',
// 'relay_user' => '<ADDR>',
// 'relay_pass' => '<PASS>',
'smtp_sender' => array(
'sender#domain.ext' => 'Sender Name'
)
);
if (isset($global_email_config['relay_host'])) {
$transport = Swift_SmtpTransport::newInstance();
$transport->setHost($global_email_config['relay_host']);
if (isset($global_email_config['relay_port'])) {
$transport->setPort($global_email_config['relay_port']);
}
if (isset($global_email_config['relay_encryption'])) {
$transport->setEncryption($global_email_config['relay_encryption']);
}
if (isset($global_email_config['relay_user'])) {
$transport->setUsername($global_email_config['relay_user']);
$transport->setPassword($global_email_config['relay_pass']);
}
} else {
$transport = Swift_SendmailTransport::newInstance();
}
$mailer = Swift_Mailer::newInstance($transport);
$logger = new Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
return array(
$logger,
$mailer
);
}

Mailchimp API - Subscribe to list

I'm working on adding a script to my site for a MailChimp subscribe form. I think I have everything setup right but when I hit the subscribe button I'm getting a blank page.
Here is the script I have currently
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->$lists->subscribe($id, $email, $double_optin=false, $replace_interests=false);
var_dump($result);
}
echo "TESTING";
So I'm not getting the $result variable or "TESTING echo'd right now, so I assume I must be doing something simple wrong. Anyone see anything obvious? I believe I'm using the correct default JSON format. (keys have been X'd out, but the one's I'm using are correct)
Any help is much appreciated.
Thanks!!
EDIT: I have updated the code to something I believe to be more correct, but it still isn't working. I could really use some help on this.
Here's how I've handled AJAX email submissions in the past for MailChimp's API (MCAPI):
define("MC_API_KEY", "Your mailchimp API key");
define("MC_API_LIST", "The list ID to subscribe user to");
define("EMAIL_TO", "email address in case subscription fails");
require "MailChimp.API.class.php";
function json($error = true, $message = "Unknown error") {
die(json_encode(array("error" => $error, "message" => $message)));
}
if(!empty($_POST)) {
$email = !empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : false;
if($email !== false) {
$api = new MCAPI(MC_API_KEY);
$result = $api->listSubscribe(MC_API_LIST, $email);
if($api->errorCode || !$result) {
if(isset($api->errorCode) && $api->errorCode == 214) { // already subscribed
json(true, "You are already subscribed!");
} else {
$error = "Unable to save user email via MailChimp API!\n\tCode=".$api->errorCode."\n\tMsg=".$api->errorMessage."\n\n";
$headers = "From: your#email.com\r\nReply-to: <{$email}>\r\nX-Mailer: PHP/".phpversion();
mail(EMAIL_TO, "Newsletter Submission FAIL [MC API ERROR]", "{$error}Saved info:\nFrom: {$email}\n\nSent from {$_SERVER['REMOTE_ADDR']} on ".date("F jS, Y \# g:iA e"), $headers);
json(false, "Thank you - your email will be subscribed shortly!");
}
} else {
json(false, "Thanks - A confirmation link has been sent to your email!");
}
} else {
json(true, "Please enter your valid email address");
}
} else json();
SOLVED:
Here is the correct code - hopefully this will help others looking to use the new api -
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once 'Mailchimp.php';
$apikey = "XXXXXXXXXXXXXXXXXXX";
$Mailchimp = new Mailchimp($apikey);
if (!empty($_POST)) {
$id = "XXXXXXXXXX";
$email = array(
'email' => trim($_POST['email'])
);
$result = $Mailchimp->lists->subscribe($id, $email, $merge_vars=null, $double_optin=false, $replace_interests=false);
}

Using swiftmailer and sending attachments

I am trying to modify a script to send a email with an attachment. It works right now but all the fields are required and I was wondering what I am missing to make it so the fields are not required.
<?php
if (($_POST)) {
$success = $error = false;
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
$dir = dirname(__FILE__);
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport());
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($post->email => $post->name, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
?>
I believe it has something to do with the foreach but if I try taking it out it breaks the whole code. If anyone can help that would be great. The reason I am taking out the validation is because i'm wanting to do it on the client side instead of server side.
you can remove the for each but then you'll have to request each posted field individually and process/validate them one at a time instead of in a loop as the loop is pulling all the post vars to local vars.
Also you don't need to require the swift mailer includes etc inside of the loop they can be moved outside of the loop as can the $mailer = new transport start line that can all go outside of the loop
EDIT WITH EXAMPLE
if (isset($_POST)) { //BAD BAD BAD way of checking there's better ways
$success = $error = false;
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$input3 = $_POST['input3'];
$input4 = $_POST['input4'];
$dir = dirname(__FILE__);
// THIS BIT IS RETARDED BUT LEAVING IT IN FOR NOW
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// END RETARDED BIT
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport());
if (isset($_FILES) && strlen($_FILES['attachment']['name']) > 0) { //here we're checking that there is attachments if there are then we're going to do the attach sw code
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($input1 => $input2, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
} else {
//non attach sw code
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($input1 => $input2, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
}
//there's better ways of doing the above but as an example this will suffice.
// Send the email, and show user message
if ($mailer->send($message)) {
$success = true;
} else {
$error = true;
}
}
?>

Categories