new to swiftmailer - inexperienced with classes

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

Post Reply
bernadette
Forum Newbie
Posts: 8
Joined: Wed Sep 12, 2007 10:43 am

new to swiftmailer - inexperienced with classes

Post by bernadette »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have had a terrible time trying to get an email class setup to send email from our local mail server as opposed to our host server...phpmailer was suggested to me first and that was relatively easy to setup but since I'm using php5 it kept kicking up errors that I was unable to find solutions for (I'm assuming that's because phpmailer is for php4)

swiftmailer was also suggested but the files were intimidating because of my inexperience with using classes and being unsure of which variables got changed where

I have uploaded all of the swiftmailer files to my includes/mailer/ directory and I've gone so far as to change at least a couple of variables, ie the host, but I'm getting such a mess of errors and I'm unable to make sense of them

the form I'm working with can be found at [url]http://www.shoppingcenter-advisor.com/moreinfo.php[/url]

any and all help is greatly appreciated and please keep in mind that I can be quite thick-headed when trying to learn this stuff so bear with me

thanks!

this is the latest error I get:
[quote]Notice: Use of undefined constant self::LOG_NOTHING - assumed 'self::LOG_NOTHING' in /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift/LogContainer.php on line 43

Fatal error: Uncaught exception 'Swift_ConnectionException' with message 'The SMTP connection failed to start [63.246.152.30:25]: fsockopen returned Error Number 110 and Error String 'Connection timed out'' in /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift/Connection/SMTP.php:309 Stack trace: #0 /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift/Connection/SMTP.php(309): Swift_Connection_SMTP::start() #1 /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift.php(216): Swift_Connection_SMTP->start() #2 /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift.php(101): Swift->connect() #3 /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/newmail.php(25): Swift->__construct(Object(Swift_Connection_SMTP)) #4 {main} thrown in /var/www/vhosts/shoppingcenter-advisor.com/httpdocs/includes/mailer/lib/Swift/Connection/SMTP.php on line 309[/quote]

this is my mail form (which is also submitting the data to a db and works just fine):

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Shopping Center Advisor - The definitive source for Shopping Center information</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="robots" content="all" />
<meta name="robots" content="index all, follow all" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/shadow.css" />
<script type="text/javascript" src="includes/shadow.js"></script>
<script type="text/javascript" src="includes/opennew.js"></script>
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>

<div id="main-wrap" class="shadow" style="display:block;">
		<div id="header"></div>
		<div id="top-nav"><?php include("includes/menu.inc"); ?>
		</div>
	<div id="col-wrap">
		<div id="left-col"></div>

		<div id="content">
	

		<p>Thank you for taking a moment to visit with us today. We hope that you've found the information contained within this site useful, and we look forward to helping you achieve your short- and long-term real estate goals.</p>
		<p>Please feel free to complete the form below and be sure to indicate whether you'd like to receive news via email. Fields marked with an asterisk (<span style="color:#ff0000;font-weight:bold;">*</span>) are required.</p>

<?php
  error_reporting('E_ALL');

include("functionlist.php");
 $conn=doconnect();
 
 if (isset($_POST['submit']))
 {
  
  if (!filled_out($_POST))
  {
    echo "<h2 style=\"color:#ff0000;\">You have not filled out the form correctly - please try again.</h2>";
  }
  
  else
  {  
    $name=$_POST['name'];
    $company=$_POST['company'];
    $title=$_POST['title'];
    $contacttype=$_POST['contacttype'];
    $phone=$_POST['phone'];
    $email=$_POST['email'];
    $timetoreach=$_POST['timetoreach'];
    $timezone=$_POST['timezone'];
    $region=$_POST['region'];
    $pricerange=$_POST['pricerange'];
    $propertytype=$_POST['propertytype'];
    $timeframe=$_POST['timeframe'];
    $updates=$_POST['updates'];
    
    mysql_query("INSERT INTO contact (name,company,title,contacttype,phone,email,timetoreach,timezone,region,pricerange,propertytype,timeframe,updates) VALUES ('$name','$company','$title','$contacttype','$phone','$email','$timetoreach','$timezone','$region','$pricerange','$propertytype','$timeframe','$updates');");
    
  }
 }
?>

			<form action="newmail.php" method="post">
				<p><label for="name" title="Name">Name<span style="color:#ff0000;font-weight:bold;">*</span>: </label>
				<input type="text" name="name" size="30" value="<?php if(isset($_POST['name'])) echo $_POST['name']; ?>" /></p>
				<p><label for="company" title="Company">Company<span style="color:#ff0000;font-weight:bold;">*</span>: </label>
				<input type="text" name="company" size="30" value="<?php if(isset($_POST['company'])) echo $_POST['company']; ?>" /></p>
				<p><label for="title" title="Title">Title<span style="color:#ff0000;font-weight:bold;">*</span>: </label>
				<input type="text" name="title" size="30" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
				<p><label for="contacttype" title="What is your function?">What is your role?: </label>
				<select name="contacttype">
					<option value="buyer">Buyer</option>
					<option value="seller">Seller</option>
					<option value="investor">Investor</option>
					<option value="1031">1031 Exchange</option>
					<option value="finance">Financier</option>				
				</select></p>
				<p><label for="phone" title="Phone">Phone (xxx-xxx-xxxx)<span style="color:#ff0000;font-weight:bold;">*</span>: </label>
				<input type="text" name="phone" size="30" value="<?php if(isset($_POST['phone'])) echo $_POST['phone']; ?>" /></p>
				<p><label for="email" title="Email">Email<span style="color:#ff0000;font-weight:bold;">*</span>: </label>
				<input type="text" name="email" size="30" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>" /></p>
				<p><label for="timetoreach" title="Best time to contact you">Best time to contact: </label>
				<select name="timetoreach">
					<option value="7am">7am</option>
					<option value="8am">8am</option>
					<option value="9am">9am</option>
					<option value="10am">10am</option>
					<option value="11am">11am</option>
					<option value="12pm">12pm</option>
					<option value="1pm">1pm</option>
					<option value="2pm">2pm</option>
					<option value="3pm">3pm</option>
					<option value="4pm">4pm</option>
					<option value="5pm">5pm</option>					
				</select></p>
				<p><label for="timezone" title="Your time zone">Time Zone: </label>
				<select name="timezone">
					<option value="eastern">Eastern, USA</option>
					<option value="central">Central, USA</option>
					<option value="mountain">Mountain, USA</option>
					<option value="pacific">Pacific, USA</option>
				</select></p>
				<p><label for="region" title="Region of interest">Region of interest: </label>
				<select name="region">
					<option value="northeast">Northeast</option>
					<option value="southeast">Southeast</option>
					<option value="midwest">Midwest</option>
					<option value="northwest">Northwest</option>
					<option value="southwest">Southwest</option>
				</select></p>
				<p><label for="pricerange" title="Price range">Price range: </label>
				<select name="pricerange">
					<option value="0-100k">$0-$100k</option>
					<option value="100k-200k">$100k-$200k</option>
					<option value="200k-500k">$200-$500k</option>
					<option value="500k-1mil">$500k-$1mil</option>
					<option value="over $1mil">over $1mil</option>
				</select></p>
				<p><label for="propertytype" title="Property type">Property type: </label>
				<select name="propertytype">
					<option value="residential">Residential</option>
					<option value="commercial">Commercial</option>
					<option value="industrial">Industrial</option>
					<option value="retail">Retail</option>
				</select></p>
				<p><label for="timeframe" title="Time frame for purchase or sale">Time frame: </label>
				<select name="timeframe">
					<option value="less than 3 months">Less than 3 months</option>
					<option value="0-3 months">0-3 Months</option>
					<option value="3-6 months">3-6 Months</option>
					<option value="9-12 months">9-12 Months</option>
					<option value="more than 12 months">More than 12 months</option>
				</select></p>
				<p><label for="updates" title="Would you like to receive future updates by email?">Select "Yes" to receive updates&sect;: </label>
				<select name="updates">
					<option value="yes">Yes</option>
					<option value="no">No</option>
				</select></p>
				<p align="center"><a href="http://www.protectwebform.com/" title="Captcha service - protectwebform.com!"><img src="http://www.protectwebform.com/images/ssl_lock.gif" style="border:none;" alt="Insure yourself from spam!" title="Insure yourself from spam!" /></a> Enter the code shown in the image:<br /><input type="text" style="vertical-align:top;"  name="protectwebformcode" value="" /> <img src="http://protectwebform.com/image/13762/" alt="Insure yourself from spam!" title="Insure yourself from spam!" /></p>
				<p align="center"><input type="submit" value="Submit" name="submit" /><input type="reset" value="Reset" name="Reset" /></p>
				
			</form>

<p style="padding-top:20px;">&sect; By selecting "Yes" and clicking on submit, you are authorizing Shopping Center Advisor to send site and feed updates to the email address you've provided.</p>
			
		</div>
		<div id="right-col"></div>
	</div>
		<div class="clearfix"></div>
		<div id="footer">
			<p>&copy;2007 <a href="http://www.ronaldmcdonald-author.com" rel="external">Ronald L. McDonald</a>. All Rights Reserved.</p>
</div>
</div>

<?php include("includes/google.inc"); ?>
</body>
</html>
the form is posting to newmail.php which contains the following:

Code: Select all

<?php

$name=Trim($_POST['name']);
$company=Trim($_POST['company']);
$title=Trim($_POST['title']);
$contacttype=Trim($_POST['contacttype']);
$phone=Trim($_POST['phone']);
$email=Trim($_POST['email']);
$timetoreach=Trim($_POST['timetoreach']);
$timezone=Trim($_POST['timezone']);
$region=Trim($_POST['region']);
$pricerange=Trim($_POST['pricerange']);
$propertytype=Trim($_POST['propertytype']);
$timeframe=Trim($_POST['timeframe']);
$updates=Trim($_POST['updates']);

require_once "includes/mailer/lib/Swift.php";
require_once "includes/mailer/lib/Swift/Connection/SMTP.php";
 
//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));
 
 
//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("63.246.152.30"));
 
 
//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
    "smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));
 
//Connect to Gmail (PHP4)
$swift =& new Swift(new Swift_Connection_SMTP(
    "smtp.gmail.com", SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_TLS));
    
    /*
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "63.246.152.30"; // SMTP server
$mail->From = $email;
$mail->AddAddress("info@shoppingcenter-advisor.com");

$mail->Subject = "Message received from Shopping Center Advisor";
$mail->Body = "Hi! \n\n This is my first e-mail sent through PHPMailer.";

$mail->Body .="Message sent from more information form:\n";
$mail->Body .="$name\n";
$mail->Body .="$company\n";
$mail->Body .="$title\n";
$mail->Body .="$contacttype\n";
$mail->Body .="$phone\n";
$mail->Body .="$email\n";
$mail->Body .="$timetoreach\n";
$mail->Body .="$timezone\n";
$mail->Body .="$region\n";
$mail->Body .="$pricerange\n";
$mail->Body .="$propertytype\n";
$mail->Body .="$timeframe\n";
$mail->Body .="Would like to receive updates: $updates\n";
$mail->WordWrap = 50;

if(!$mail->Send())
{
   //print "<meta http-equiv=\"refresh\" content=\"30;URL=no.php\">";
   echo 'Message was not sent.';
   echo 'Mailer error: ' . $mail->ErrorInfo;
/* if ($success)
  {
    print "<meta http-equiv=\"refresh\" content=\"0;URL=yes.php\">";
  }
else
  {
    print "<meta http-equiv=\"refresh\" content=\"0;URL=no.php\">";
  } 
}
else
{
    print "<meta http-equiv=\"refresh\" content=\"0;URL=thankyou.php\">";
   echo 'Message has been sent.';
}   */
?>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
chuckl
Forum Commoner
Posts: 61
Joined: Wed May 23, 2007 7:36 am

Post by chuckl »

Bernadette, If you find the classes intimidating, ignore them and concentrate on what you want to do. You'll find that in a well constructed package like Swiftmailer, there is a class that mimics that closely, and you use that class to achieve your purpose. Looking at your code, you're trying too hard. It's not that complicated.

e.g. In order to send mail, you need a connection to a mail server. Note, a connection. So create a connection. In your case, it seems you want an SMTP connection. Create an SMTP connection, and while you're at it, specify the host to which you want to connect, and any encryption, authentication, ports etc you want to use.

Make a simple connection.

Code: Select all

$smtp = new Swift_Connection_SMTP("mail.mydomain.com");
That'll create a new SMTP connection, to my mail server, using every default in the book, and with no authentication.

For a complex connection, e.g. Gmail, you need to specify the ports, encryption etc. Already exists with predefined constants.

Code: Select all

$smtp = new Swift_Connectio_SMTP("smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS);

In the case of Gmail, you need to add authentication, user name and password. So, add them

Code: Select all

$smtp = new Swift_Connectio_SMTP("smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS);
$smtp->setUsername('username");
$smtp->setPassword(password);

Now that you have a connection defined, you need a message to send. So create one

Code: Select all

$message = new Swift_Message($email_subject);
Note that we've included the subject in the definition, it could be added later. We now have a message.


Take all of your form output, by whatever means and coding necessary, just like phpMailer, and stick it into the message body. In addition, lets be smart and attacha plain text version as well.

Code: Select all

$message->attach(new Swift_Message_Part($text, "text/plain", $Encoding, $CharSet));
$message->attach(new Swift_Message_Part($email_html, "text/html", $Encoding, $CharSet));

We might do some housekeeping on return paths, ounce addresses, that sort of thing, but we're ready to go.

So now we tell Swift to put it all together and send our message, but first step is to have an instance of Swift.
So

Code: Select all

$swift = new Swift($smtp);

i.e. create a Swift object using our previously defined connection


And then send our message with all the bits and pieces.

Code: Select all

$swift->send( $message, $recipients, new Swift_Address($from_email_address, $from_email_name));
And we're done.

One thing I did leave out is to create a recipients list, which you do like this:

Code: Select all

$recipients =& new Swift_RecipientList();
$to_name = "some name";
$to_email_address = "someemail@address";
$recipients->addTo($to_email_address, $to_name);
And thats it, give or take a couple of hundred lines of code.

If you take the phpMailer code, it is very easy to change the php mailer calls to swift calls.

Hope that helps
bernadette
Forum Newbie
Posts: 8
Joined: Wed Sep 12, 2007 10:43 am

Post by bernadette »

first let me apologize for not using the proper tags - clicked the wrong one

second - WOW - I never expected such a detailed response that contained such worthwhile advice...unfortunately I must wait until a server issue gets corrected before I can try again - apparently a second smtp client was inadvertently installed on the server and it will be a day or 2 before it can be corrected

as far as your comment about me trying too hard - I always have a tendency to overanalyze things - especially when they're new to me and is one of the reasons I left the phpmailer code commented out

thank you so much for your detailed instruction and I look forward to being able to use it in the next day or so
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

If you're not used to OOP (classes) then don't be afraid to just blindy copy & paste my code from the wiki, changing the obvious bits to fit your needs. You'll probably start to see patterns in the way things are put together and be able to make educated guesses on how to do things. I'd like to think that the organisation of the Swift Mailer provides some insight into Object Oriented design for newcomers too. It generally reads very logically once you get over the syntax you're probably not familiar with ;)
chuckl
Forum Commoner
Posts: 61
Joined: Wed May 23, 2007 7:36 am

Post by chuckl »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


You're most welcome Bernadette, if it's not obvious from my reply, I've been involved indoing exactly what you are attempting - replacing phpMailer.

Ther's nothing wrong with overanalysing - think first, then code.

You sample code was creating 4 instances of swift, or rather recreating? Not necessary, in fact probably fatal. I think I'm right in saying that Swiftmailer attempts to connect as soon as the swift instance is created, so it's important to define the connection completely first.

Define a connection.
Create a message and define sender recipient etc
Create a swift instance with the connection and send the message.
Thats it.

On the message side, the existing phpMailer code will probably create the message text or html body, all properly formatted etc. This is usually then passed to phpmailer in something like this:

Code: Select all

if (EMAIL_USE_HTML == 'true') {
        $mail->IsHTML(true);           // set email format to HTML
        $mail->Body    = $email_html;  // HTML-content of message
        $mail->AltBody = $text;        // text-only content of message
      }  else {                        // use only text portion if not HTML-formatted
        $mail->Body    = $text;        // text-only content of message
      }
Simply take those variables as appropriate once they have been verified, formatted etc, attach them to the Swiftmailer message, and send.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Post Reply