Swift Mailer tutorial

Swift Mailer is a fantastic library for sending email with php. Discuss this library or ask any questions about it here.

Moderators: Chris Corbyn, General Moderators

User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

magic_quotes still confuses me at times. It's a "feature" PHP has which adds \ characters before things like " and ' and and \. It causes more of a nuisance than a helping hand so it's being dropped in future releases of PHP. Not only does it cause a problem, there are 3 variations of it: "gpc", "runtime" and "sybase".

You're right in that I'm the main developer. I'm actually the sole developer as of now. I'm hoping to open up the project on SourceForge to new developers once the new version settles in.

Glad you got it working anyway :)
JeffBell
Forum Newbie
Posts: 15
Joined: Thu Feb 01, 2007 8:17 am

Post by JeffBell »

Some do-gooder's magic_quotes idea was helpful to the point of annoying, eh? I think I read somewhere that I turn that off by using an .htaccess file (but make sure all your PHP stuff is compatible without magic_quotes before you do that, I would imagine).

If you're doing this alone, you're kicking some serious tail.

Yes, I've actually spent many more hours cajoling it into the shape I want! It's working great.

I did have questions about the paint_value operation. After some wrangling, I managed to organize everything correctly but learned that it does not work for radios and selects. If you have (or anyone lurking has!) a free moment to point me in the right direction, that would be helpful. I searched google for examples of "php post form values" but that was a mess. :wink:

Okay, I want to leave a tip for anyone else reading this tutorial, after working on this a while. You'll notice that when you receive the email from your contact form, it does not have the sender's actual name in the from field. But you can fix that by modifying a couple lines in Step 12.

Code: Select all

/** 12 **/
//Try sending the email.
// Redirect to success page on success, or form on failure
if ($swift->send("yourname@example.com", $email, $subject))
The reason why, as you see, is the second value could have been "My Name" <sender@somewhere.com> but it is only inserting the email address. If you want the name to appear, then you could replace it with this

Code: Select all

/** 12 **/
//setup the sentfrom
$sentfrom = '"' . $user_name . '" <' . $email . '>';
//Try sending the email.
// Redirect to success page on success, or form on failure
if ($swift->send("yourname@example.com", $sentfrom, $subject))
Or, if you're like me and separated first and last name to two different input boxes, then you can do this instead.

Code: Select all

/** 12 **/
//setup the sentfrom
$sentfrom = '"' . $firstname . ' ' . $lastname . '" <' . $email . '>';
//Try sending the email.
// Redirect to success page on success, or form on failure
if ($swift->send("yourname@example.com", $sentfrom, $subject))
Just be sure to watch those quotes! They change from ' and " in a specific way... and cost me a dear amount of time to sort that out properly.

EDIT

Here's another tip. If you want to send to the contact form email to multiple people, you can follow the ideas shown here.
http://www.swiftmailer.org/docs/tutorials/batch-mailing

Now, if you're similar to me and MySQL looks like mumbo jumbo, then you can just type the list out. Basically, you follow the pattern laid out on that page, which after some trial-and-error successfully looks something like this.

Code: Select all

/** 12 **/
//setup the sentfrom
$sentfrom = '"' . $firstname . ' ' . $lastname . '" <' . $email . '>';
//sent to multiple people
$sendtolist = array ("yourname@example.com", "yourfriend@gmail.de", "yourboss@whipcrackers.net");
//Try sending the email.
// Redirect to success page on success, or form on failure
if ($swift->send($sendtolist, $sentfrom, $subject))
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Note that version 3 include a (simple) Address object:

Code: Select all

$sender = new Swift_Address("Foo@bar.com", "Mickey Jones");
It's completely optional, but if you don't use it, Swift will parse the string form of the address and produce an address object anyway.
lunarman
Forum Newbie
Posts: 4
Joined: Mon Feb 12, 2007 12:08 pm

Post by lunarman »

Hi,

I'm very new to PHP, but have succesfully got Swift Mailer running on my site as per this tutorial. However, I need to be able for the users to select the email recipient from a drop-down select box.

I have made the following changes to the tutorial code:

In mail_handler.php

Code: Select all

if ($recip == 'fish') {
   $addy = "email address 1";
} elseif ($recip == 'ships') {
   $addy = "email address 2";
}
then later

Code: Select all

if ($swift->send($addy, $email, $subject))
In contact.php, I added the following to the Form

Code: Select all

<div class="row">
        <div class="label">Select<span class="required">*</span></div>
        <div class="field">
			<select name="recip">
				<option value="fish">Fish</option>
				<option value="ships">Ships</option>
			</select>
        </div>
    </div>
I think that the value is not getting from the form into $recip, as if I add

Code: Select all

$recip = 'ships';
just before the code in mail_handler.php, it works.

Can anyone help a newb?

Thanks,
Lunarman
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post by nickvd »

Your code is expecting Register Globals to be on. Apparently your server has it off (as it should, as it poses a fairly large security risk).

The correct way to access GET and POST variables is to use $_GET and $_POST.

Code: Select all

if ($_POST['recip'] == 'fish') { //...and so on (assuming your form uses POST)
lunarman
Forum Newbie
Posts: 4
Joined: Mon Feb 12, 2007 12:08 pm

Post by lunarman »

nickvd,

Many thanks.. works perfectly.

Regards,

Lunarman
lunarman
Forum Newbie
Posts: 4
Joined: Mon Feb 12, 2007 12:08 pm

Post by lunarman »

Hi again,

One other small issue with the tutorial. The email validation doesn't seem to be working for me. Here's the (unchanged) code from the tute:

Code: Select all

/** 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: ../contact.php?error=email_invalid");
    exit();
}
A message with just 'g' as email address get's sent fine. All other errors are reported correctly.

Can anybody help with this please?

Regards,
Lunarman
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

The regexp will accept "g" or "foo" or "bar" etc as valid email addresses. Internal mailing software often uses "local addresses" in this form.

If you'd rather not allow that, just take out the trailing "?" in $email_re

Code: Select all

$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))';
PS: When posting PHP code in the forums please use

Code: Select all

 [/php ] tags not [code ] [/code ] ;)
lunarman
Forum Newbie
Posts: 4
Joined: Mon Feb 12, 2007 12:08 pm

Post by lunarman »

d11wtq wrote:The regexp will accept "g" or "foo" or "bar" etc as valid email addresses. Internal mailing software often uses "local addresses" in this form.
Ah, I see.
If you'd rather not allow that, just take out the trailing "?" in $email_re
So simple! Still got much to learn.
PS: When posting PHP code in the forums please use

Code: Select all

 [/php ] tags not [code ] [/code ] ;)[/quote]
Oops! Will do. Never noticed the option.

Many thanks for your help, and all your work on Swiftmailer

Regards,
Lunarman
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

FYI, here's the version 3 form-to-mail tutorial:

http://www.swiftmailer.org/wikidocs/v3/form2mail
JeffBell
Forum Newbie
Posts: 15
Joined: Thu Feb 01, 2007 8:17 am

Checkboxes (in v2)

Post by JeffBell »

I've continued to use the Swift Mailer since you first helped me get going. I'm staying with v2 for the time being, but will eventually move to v3 in the near-ish future.

For today's puzzle, I seem to be unable to get checkbox values to post (or print to the email body, anyway). Here's the example from the actual form. At first, I tried to name them all marketsource, but later read somewhere I needed to have a backeted value [x] for reasons I do not fully understand.

Code: Select all

How did you hear about us?<br />
					<input type="checkbox" name="marketsource[1]" value="Barney" /> Barney
					<input type="checkbox" name="marketsource[2]" value="Waldo" /> Waldo
					<input type="checkbox" name="marketsource[3]" value="Dr. Who" /> Dr. Who
					<input type="checkbox" name="marketsource[4]" value="McGruff" /> McGruff<br />
					<input type="checkbox" name="marketsource[5]" value="Grommit" /> Grommit
					<input type="checkbox" name="marketsource[6]" value="Vegemite" /> Vegemite
					<input type="checkbox" name="marketsource[7]" value="Marmite" /> Marmite<br />
					<input type="checkbox" name="marketsource[8]" value="Dolemite" /> Dolemite
					<input type="checkbox" name="marketsource[9]" value="Other" /> Other
And then, like text fields and radios (which work fine), I asked the parsing script to get the data and set it as variable.

Code: Select all

$marketsource = $_POST["marketsource"];
Lastly, I wanted to the script to write the values to the email but only if there was marketsource data posted, with

Code: Select all

if (!empty($marketsource))
{
    $body .= "The contact indicated they found us via the following source(s): " . $marketsource . "\r\n";
}
But the email just comes up empty. The reason why I think the data is not posting is because my little preamble (above) in the email body does not appear. Thus, $marketsource must be empty. But when filling out the form, I check the boxes, so it should have data.

Any help?

Ultimately, I'd like to have multiple values be comma separated in the email body (e.g., "Barney, Marmite, Other").
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

$_POST["marketsource"] will be an array (that's what the [] are for in the form). implode() it:

Code: Select all

$marketsource = implode(", ", $_POST["marketsource"]);
EDIT | PS, please start using

Code: Select all

 [/ php] tags rather than [code ] [/ code] tags when posting PHP code :)
JeffBell
Forum Newbie
Posts: 15
Joined: Thu Feb 01, 2007 8:17 am

Post by JeffBell »

I hesitate to ask for further help, but after researching online for a day I am unable to solve this. Once I used the implode command (and the syntax looks totally correct), then it generates an error/conflict the header.

Here is the php I used, which I didn't need to change your example (Line 50)

Code: Select all

$marketsource = implode(", ", $_POST["marketsource"]);
//$marketsource = $_POST["marketsource"];
Here is where the header is supposed to be set, but only SINCE adding the implode command have I gotten an error. Before that, it was working just fine.

Code: Select all

{
    unset($_SESSION["post"]); //It worked, we have no reason to keep this data
    $swift->close();
    header("Location: contact_us_thanks.php"); /** 13 **/
    exit();
}
And, of course, here's the specific error.

Code: Select all

Warning: implode(): Bad arguments. in /usr/local/apache/hosts/domain/pub/parseandsend.php on line 50

Warning: Cannot modify header information - headers already sent by (output started at /usr/local/apache/hosts/domain/pub/parseandsend.php:50) in /usr/local/apache/hosts/domain/pub/parseandsend.php on line 158
Any thoughts on what I need to look into? I couldn't find any reasons. (Yes, the session is properly started on the original contact_us.php page. No, there are no extra spaces at the end of the parseandsend.php document after the php tags close.)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

What does:

Code: Select all

var_dump($_POST["marketsource"]);
Show?
JeffBell
Forum Newbie
Posts: 15
Joined: Thu Feb 01, 2007 8:17 am

Post by JeffBell »

Thanks for the diagnostic command. It shows

Code: Select all

string(5) "Array"
UPDATE
Should I be doing this?

Code: Select all

$marketsource = array(); 
$marketsource = implode(", ", $_POST["marketsource"]);
Does that somehow clarify it's an array before imploding it? I'm just Googling and reading similar-but-different problems.

UPDATE to the UPDATE
Well, so far, that was my only guess after reading various other forums and such. Unfortunately, that solution doesn't do anything.
Post Reply