Page 1 of 1

ERROR: Undefined Method: Swift::addAttachment() [SOLVED]

Posted: Sun Jan 06, 2008 7:04 pm
by MichaelGallagher
Hi,

I am using latest versions of Apache, MySQL and PHP (XAMPPLite), also using Zend to develop.

I have some data being pulled from a database and put into an email that is then sent via a form (where sender chooses recipients and attaches a file if necessary) and I have tried several different methods and scripts.

I am looking to get your basic script working, and then modify it to include the database information and correct form layout, etc.

Here is the basic script i am using (I believe i got it from another posted topic):

Code: Select all

<?php

//Start session
session_start();

//Function to display the values in the fields
function paint_value($field)
{
    if (!empty($_SESSION["post"][$field]))
    {
        echo $_SESSION["post"][$field];
    }
    else { echo ""; }
}

//Check if errors were sent
if (!empty($_GET["error"]))
{
    switch ($_GET["error"])
    {
        case "incomplete":
            $field_labels = array("user_name" => "Name", "email" => "E-mail address", "subject" => "Subject", "comments" => "Comments");
            $incomplete = explode(",", $_GET["fields"]);
            ?><div class="error">All required fields (*) were not completed.  Please check the following fields:
                <ul>
                    <?php foreach ($incomplete as $field) {
                        if (isset($field_labels[$field])) { echo "<li>" . $field_labels[$field] . "</li>"; }
                    } ?>
                </ul></div><?php
            break;
        case "email_invalid":
            ?><div class="error">The email address entered does not appear to be a valid format</div><?php
            break;
        case "attachment_failed":
            ?><div class="error">The attachment upload failed.  Perhaps the file is too large?</div><?php
            break;
        case "runtime_error":
            ?><div class="error">There was a problem processing your request.  Please try again later.</div><?php
            break;
    }
}

?>
<form action="mail_handler.php" method="post" enctype="multipart/form-data">
    <div class="row">
        <div class="label">Your name*:</div>
        <div class="field"><input type="text" name="user_name" value="<?php paint_value("user_name"); ?>" /></div>
    </div>
    <div class="row">
        <div class="label">Your e-mail*:</div>
        <div class="field"><input type="text" name="email" value="<?php paint_value("email"); ?>" /></div>
    </div>
    <div class="row">
        <div class="label">Subject*:</div>
        <div class="field"><input type="text" name="subject" value="<?php paint_value("subject"); ?>" /></div>
    </div>
    <div class="row">
        <div class="label">Attachment:</div>
        <div class="field"><input type="file" name="attachment" /></div>
    </div>
    <div class="row">
        <div class="label">Comments*:</div>
        <div class="field"><textarea name="comments"><?php paint_value("comments"); ?></textarea></div>
    </div>
    <div class="row">
        <div class="label">&nbsp;</div>
        <div class="field"><input type="submit" name="submit" value="Send" />
    </div>
</form>
After filling out the form with test data, and attaching a test.txt file, the error message I receive is:

Fatal error: Call to undefined method Swift::addAttachment() in C:\xampplite\htdocs\corporate\mail_handler.php on line 100

The mail_handler.php is unmodified:


Code: Select all

<?php

/** 1 **/
session_start();

/** 2 **/
//See if evil magic_quotes is enabled, and fix problems if it is
$quotes_on = (get_magic_quotes_gpc() || get_magic_quotes_runtime());
if ($quotes_on)
{
    foreach ($_POST as $key => $value)
    {
        $_POST[$key] = stripslashes($value);
    }
}

/** 3 **/
$_SESSION["post"] = $_POST;

/** 4 **/
//Load in the required Swift files
require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";

/** 5 **/
//Create an empty array where we can catch any fields which were not filled in
$fields_not_set = array();

//Check if all POST data was sent, redirect with an error if not
if (empty($_POST["user_name"])) $fields_not_set[] = "user_name";
if (empty($_POST["email"])) $fields_not_set[] = "email";
if (empty($_POST["subject"])) $fields_not_set[] = "subject";
if (empty($_POST["comments"])) $fields_not_set[] = "comments";

//If $fields_not_set contains any values, then something wasn't filled in. Time to redirect.
if (!empty($fields_not_set))
{
    //Read further down to see how we'll modify form.php to handle the error
    header("Location: form.php?error=incomplete&fields=" . implode(",", $fields_not_set));
    exit();
}

//Copy the POST data to standard globals
$user_name = $_POST["user_name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$comments = $_POST["comments"];

/** 6 **/
//This is a RegExp I've adopted for validating email addresses.  NOTE that it's NOT RFC compliant.
// Use another regexp at your own choice
$email_re = '(?#Start of dot-atom
                )[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+(?:\.[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+)*(?#
                End of dot-atom)(?:@(?#Start of domain)[-0-9A-Za-z]+(?:\.[-0-9A-Za-z]+)*(?#End of domain))?';

//Now check if the email address they gave is valid, redirect back to the form if not
if (!preg_match('/^' . $email_re . '$/', $email))
{
    header("Location: form.php?error=email_invalid");
    exit();
}

/** 7 **/
$attachment_data = array();
//Now check if there's an attachment they've sent
if (!empty($_FILES["attachment"]["tmp_name"]))
{
    //If an attachment was sent, but there was an error, redirect
    if ($_FILES["attachment"]["error"] != 0)
    {
        header("Location: form.php?error=attachment_failed");
        exit();
    }
    else $attachment_data = $_FILES["attachment"];
}

/** 8 **/
//Everything looks ok to send an email, create an instance of Swift
$swift = new Swift(new Swift_Connection_SMTP("mail.w3style.co.uk"));

/** 9 **/
//Now build your message body
$body = "A message was sent from " . $user_name . " with the title '" . $subject . "'";
if (!empty($attachment_data))
{
    $body .= "\r\nAn attachment with the name '" . $attachment_data["name"] . "' was added";
}

/** 10 **/
//Attach any files if they were sent
// PHP stores files in a temporary location and cleans up itself, so we'll just read the temporary file
if (!empty($attachment_data))
{
    $attachment_str = file_get_contents($attachment_data["tmp_name"]);
    //Check if we need to remove slashes (again!!)
    if ($quotes_on)
    {
        $attachment_str = stripslashes($attachment_str);
    }
    $swift->addAttachment(
        $attachment_str, $attachment_data["name"], $attachment_data["type"]);
}

/** 11 **/
//Add the email body
$swift->addPart($body);

/** 12 **/
//Try sending the email.
// Redirect to success page on success, or form on failure
if ($swift->send("chris@w3style.co.uk", $email, $subject))
{
    unset($_SESSION["post"]); //It worked, we have no reason to keep this data
    $swift->close();
    header("Location: success.php"); /** 13 **/
    exit();
}
else
{
    $swift->close();
    header("Location: form.php?error=runtime_error"); /** 13 **/
    exit();
}


//End of script
Both of these files, form.php & mail_handler.php, are in the HTDOCS folder.

Any help us much appreciated.

Mick

EDIT: grammatical.

Posted: Sun Jan 06, 2008 7:52 pm
by Chris Corbyn
The addAttachment() and addPart() methods are not part of the Swift class, but are actually part of the Swift_Message class. I'd probably suggest reading the documentation on the website and re-reading the code where you got this from ;)

http://www.swiftmailer.org/wikidocs/v3/ ... ttachments

oops! please forgive me!

Posted: Sun Jan 06, 2008 8:42 pm
by MichaelGallagher
:oops:

Lol! I have reviewed my post, my code, and my directory structure.

All the smoke tests are working fine, and now I know where I am going from there.

Sorry about that, it seems a coffee on the first morning of work for the year should have been a priority.

Thanks for that though,

Mick :wink:

EDIT: Feel free to delete this useless post..

Re: oops! please forgive me!

Posted: Sun Jan 06, 2008 9:40 pm
by Chris Corbyn
MichaelGallagher wrote:Feel free to delete this useless post..
Your post is actually a pretty useful one. You're not the first person to make that mistake and you won't be the last. Being able to search for that error and see this thread with a resolution is definitely helpful for others ;)

Good luck!