PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sat Oct 19, 2019 11:03 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 37 posts ]  Go to page 1, 2, 3  Next
Author Message
 Post subject: Swift Mailer tutorial
PostPosted: Thu Feb 01, 2007 9:36 am 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 10:10 am 
Offline
Forum Contributor
User avatar

Joined: Tue May 23, 2006 10:42 am
Posts: 351
You would set your form action to the page that you want to handle sending the email. The code example is the code you would put inside the email handler (ie, form action='mypage.php', put that code in mypage.php).

Syntax: [ Download ] [ Hide ]
$swift->send('recipient@address.com', 'sender@address.com', 'The subject', 'The body');


That's where the email is actually being sent. Just fill out the required pieces and you have an email. If you want to have a little bit more format to your email, you can do something along the lines of:

Syntax: [ Download ] [ Hide ]
$body = "Hello  " . $_POST['name'] . "!";

$swift->send('recipient@address.com', 'sender@address.com', 'Good Morning!', $body);


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 11:10 am 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia
I will improve the documentation over time. Right now I'm working on the library itself but because it's only me developing the library and maintaining the documentation on a purely voluntary "on my own time" basis things may not move as quickly as people would like. I'm sorry about that :(

However, I would suggest that you should perhaps try getting to grasps with the basics of PHP and forms (using $_POST, $_GET etc) by reading some more generic tutorials at php.net and by searching Google until I can find time to improve the documentation.

I'm moving documentation to a wiki which I can perhaps put some trust (of course I can :)) in users to edit in the long run.

Have you looked at general contact form tutorials? The Swift part is basic once you know how a contact form would generally be implemented with something like the mail() function.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 11:13 am 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia
If I get time when I get home from work I'll post a tutorial here.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 12:10 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 2:15 pm 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 3:42 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15
A quick update to let you know I think I've understood what you laid out here.

Currently, I'm debugging to try to get the example to run.

Once that's done, then I'll try modifying some bits and pieces based on what I learn by experimenting... and from the documentation because I am already guessing it will be more valuable/understandable to me once I've gotten this leg-up you're giving me.

I can't say how much I appreciate the instruction. I'll probably be back before long with an intelligent question and two stupid ones as I get this test version to work.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 4:21 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 4:39 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 4:40 pm 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia
Doh... that was just a token for part of a regexp since I use it in larger expressions:

Syntax: [ Download ] [ Hide ]
//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();

}


PS: I didn't test the code. Was in a rush to type it. It was supposed to be a guide rather than a copy & paste example ;)


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 5:27 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15


Last edited by JeffBell on Thu Feb 01, 2007 6:48 pm, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 6:28 pm 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia
Here are the tested working scripts. All I changed was the regexp which was already posted earlier, and a missing "=" iin enctype in the form.

Syntax: [ Download ] [ Hide ]
<?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 "classes/Swift.php";

require_once "classes/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


Syntax: [ Download ] [ Hide ]
<?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>


This works, I have tested it. End your files with a blank new line by the way.

EDIT | Also fixed the check for if a file was uploaded to check for non-empty tmp_name.

You can download it here to save copy & pasting. Note that the file was written on a Mac so the line ending is \n and some windows editors won't display it correctly.

http://www.w3style.co.uk/~d11wtq/swifttest.zip 51Kb


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 6:46 pm 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15
I can see now that I fat-fingered the disappearing } bracket. Your original code was just fine. Strictly my doing and I've removed those comments.

I did correct the enctype= earlier, but thanks for covering it just in case.

I set up a successful test! 8) I can get the email sent with the attachment on it. One small problem, I was attaching a PDF and it arrived at full size (78K) but it was blank. The original file is definitely not blank.

Any ideas on where I went wrong? I did close the php tag on mail_handler, but I now see you say to leave it open. Could that be the reason the attachment was corrupted? Or is it because the mime type was not set, as talked about here?
http://www.swiftmailer.org/docs/composi ... attachment

Also, my first attachment returned a "too big" error. I didn't see any notation on the Swift Mailer site about sizes; what is the limit? Is that configurable? Just curious. I don't need 800mb attachment limits, but it would be nice to how it's set up.

Thanks again!


Top
 Profile  
 
 Post subject:
PostPosted: Thu Feb 01, 2007 7:03 pm 
Offline
Breakbeat Nuttzer
User avatar

Joined: Wed Mar 24, 2004 8:57 am
Posts: 13098
Location: Melbourne, Australia


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 02, 2007 7:12 am 
Offline
Forum Newbie

Joined: Thu Feb 01, 2007 9:17 am
Posts: 15
I've been meaning to try this earlier today, but only now got the time. I commented out that line and, yes, the attachments arrive unharmed now.

I will check my example code against the last version you posted above and compare for any differences. And then I'll look into this subject of stripslashes and the issue of forcedownload versus octetstream mime types.

After that, I'll be off creating the forms and functions I want. If I have new questions, I'll write in either a new thread or an existing one (if its on topic).

But, you've essentially provided an excellent tutorial right here which really gets a newbie/non-programmer up and running!

Thank you very much for your effort.

I noticed that you seem to be the main developer of Swift Mailer, actually. (I guess I stumbled into the right place to ask!) I will become a modest donor, for sure, and will make sure it includes a note to reference this discussion so that you know.

EDIT

I was just looking up the tmp_name issue and I found it's a matter of security, apparently.
http://shiflett.org/articles/file-uploads

There, that author suggests using an extra 'if' to verify the attachment is the same as what was uploaded (how that could not be true is something I do not understand). I had been thinking to try to implement that, but it turned out very complicated for me to try integrating it. Nonetheless, I'll leave the link for others.

Also, at the same site, the guy suggests a possible way to check file size. Frankly, I'm not too sure I understand what would happen (in terms of what the user would see) if that code were used and the attachment was deemed too big. But, I was just noting it here for future reference because it seems to address the issue on some level or other.


Last edited by JeffBell on Fri Feb 02, 2007 10:15 am, edited 2 times in total.

Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 37 posts ]  Go to page 1, 2, 3  Next

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group