22
Sun, Dec
3 New Articles

TechTip: Email Made Simple(r) with PHP and Pear

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Wouldn't it be great if we could bypass the IBM i SMTP and POP servers altogether? Well, we can!

 

I've written several TechTips related to improving your ability to send email effectively from your IBM i (See "TechTip: Use PHP and Zend_Mail to Send Email" and "TechTip: Using the QTMMSENDMAIL API"). This TechTip is the latest installment in that genre. It had to be done because the tools just keep getting better and easier to use.

 

The first piece of good news is for all of you who are not experts with the SMTP and POP server configuration on IBM i. You will not be using the IBM i SMTP and/or POP server! (Go back and read that last sentence again; I think it bears repeating.) That's right! We're going to bypass the IBM i servers altogether. The reason for this is twofold. First, it allows you to avoid the headaches of configuring them. Second, it allows you to use an external email server (Gmail, AIM, or Lavabit, for example) to forward all your outgoing emails from the IBM i. What we're going to do is write an email script that connects to your external email server the same way that Outlook does: using SSL ports.

 

The first thing you'll need is to have PHP installed on your IBM i. Next, you'll need to install a couple of Pear extensions (unless you already have them): the Mail extension and the Mail_Mime extension. These extend the normal PHP email functionality quite a bit. If you're familiar with Pear extensions and the Pear installer, then you can use the installer to install the extensions. However, if you aren't, just copy the files contained in the Mail-1.2.0.tgz and Mail_Mime-1.6.0.tgz files to the IFS directories shown below:

 

Mail-1.2.0.tgz                à  /usr/local/Zend/Core/share/pear/Mail

Mail_Mime-1.6.0            à  /usr/local/Zend/Core/share/pear/Mail_Mime

 

Once you have done this, we're ready to start coding our script to send email messages. The code is pretty easy to follow, but it does use classes and object-oriented methodologies. As always, if you are inexperienced with classes and OO, then I highly recommend that you take some time to familiarize yourself with them. (I'm stepping off my soapbox now.)

 

The code below will send a very simple email:

 

<?php

// setup error reporting for testing/development

ini_set("ERROR_REPORTING", E_ALL);

error_reporting(E_ALL);

// set include path to include PEAR directory

ini_set("include_path", ini_get("include_path").":/usr/local/Zend/Core/share/pear");

// require the PEAR Mail and Mail_Mime classes

require_once "Mail/Mail.php";

require_once "Mail_Mime/mime.php";

// setup external mail connection parameters

$host = "ssl://smtp.gmail.com";

$port = "465";

$username = "username";

$password = "password";

// load recipient and subject

$to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$subject = "test email";

// Text body

$bodyText = "This is the body text of the email.";           

// HTML body

//$bodyHTML = "<html><h3><font color='red'><i>This is the HTML text of the email</i></font></h3></html>";

$message = new Mail_Mime();

$message->setTXTBody($bodyText);

// $message->setHTMLBody($bodyHTML);

$body = $message->get();

$extraheaders = array("From"=>"Jeff Olen <This email address is being protected from spambots. You need JavaScript enabled to view it.>", "Subject"=>$subject);

$headers = $message->headers($extraheaders);

$mail = Mail::factory('smtp',

  array ('host' => $host,

    'port' => $port,

    'auth' => true,

    'username' => $username,

    'password' => $password));

   

$rs = $mail->send($to, $headers, $body);

if (PEAR::isError($rs)) {

  echo("<p>" . $rs->getMessage() . "</p>");

 } else {

  echo("<p>Message successfully sent!</p>");

 }

 

Let's go through each step.

 

First, we're preparing for testing and development by setting up to report all errors.

 

<?php

// setup error reporting for testing/development

ini_set("ERROR_REPORTING", E_ALL);

error_reporting(E_ALL);

 

 

Next, we're adding the PEAR directory to the include path. This is a list of directories that will be searched for INCLUDEd or REQUIREd files. Then, we actually pull in the PEAR modules we need using the REQUIRE_ONCE function.

 

// set include path to include PEAR directory

ini_set("include_path", ini_get("include_path").":/usr/local/Zend/Core/share/pear");

// require the PEAR Mail and Mail_Mime classes

require_once "Mail/Mail.php";

require_once "Mail_Mime/mime.php";

 

Now, we set up the mail connection parameters. Note that the code shown is not the recommended way to do this. We are only including the username and password in the clear as an example. This information should be pulled in from a secured script using a REQUIRE function.

 

// setup external mail connection parameters

$host = "ssl://smtp.gmail.com";

$port = "465";

$username = "username";

$password = "password";

 

If you're using Gmail, these are the actual host and port that you'll need. If you're using a different email provider, you'll need to check with that provider for the actual settings. Or if you have the correct setup in Outlook, you can get the information from there.

 

Now, we load the recipient email address and subject line.

 

Then, we have two options for the body of our email; either plain text or HTML. If you want to use HTML for your message body, you'll need to use the setHTMLBody method instead of the setTXTBody method. I have included that code as well, but it is commented out.

 

The last thing we do in this section of code is use the Mail_Mime method "get" to load the mail message body in the variable called $body.

 

// load recipient and subject

$to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$subject = "test email";

// Text body

$bodyText = "This is the body text of the email.";           

// HTML body

//$bodyHTML = "<html><h3><font color='red'><i>This is the HTML text of the email</i></font></h3></html>";

$message = new Mail_Mime();

$message->setTXTBody($bodyText);

// $message->setHTMLBody($bodyHTML);

$body = $message->get();

 

In the next section of code, we put together some header information. This is similar to the Zend_Mail header information from the previous article. We're just setting up the "From" line and "Subject" line for the email to be sent. Then, we use the Mail_Mime function "headers" to output the actual mime headers and place them in the $headers variable.

 

Now, we create a Mail object called $mail. To do this, we are using the scope resolution operator (the double-colon in Mail::factory) to access and override properties in the Mail class. In this case, we want to use the SMTP mail driver, and we want to use the parameter values listed in the array that follows. This returns the $mail object, which we then use to execute the actual mail send.

 

Lastly, we check to make sure the email was sent successfully and echo an appropriate response.

 

$extraheaders = array("From"=>"Jeff Olen <This email address is being protected from spambots. You need JavaScript enabled to view it.>", "Subject"=>$subject);

$headers = $message->headers($extraheaders);

$mail = Mail::factory('smtp',

  array ('host' => $host,

    'port' => $port,

    'auth' => true,

    'username' => $username,

    'password' => $password));

   

$rs = $mail->send($to, $headers, $body);

if (PEAR::isError($rs)) {

  echo("<p>" . $rs->getMessage() . "</p>");

 } else {

  echo("<p>Message successfully sent!</p>");

 }

 

The Mail object method "send" has three parameters, which are described below:

 

Parmeter 1: Mail recipient(s)—In our example, we had just one recipient, so this parameter was a simple string. We could have just as easily loaded an array with email addresses and used that as parameter 1. For example: 

 

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

...

...

...

$rs = $mail->send($recipients, $headers, $body);

 

Parameter 2: The headers—This is the additional header information including the "From" email address and Subject line.

 

Parameter 3: The actual body of the email.

 

That's it for our example script. But let me offer you a few tips on ways to extend the functionality of this script. First, as I mentioned in the section about the Mail "send" parameters, you can send to multiple recipients. You can also carbon copy emails as shown below, but you must add the extra headers to determine which email addresses are just normal "to" and which are "cc."

 

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

$recipients[] = "This email address is being protected from spambots. You need JavaScript enabled to view it.";

...

$extraheaders = array("From"=>"Jeff Olen <This email address is being protected from spambots. You need JavaScript enabled to view it.>", "Subject"=>$subject, "To"=>"This email address is being protected from spambots. You need JavaScript enabled to view it.",

"Cc"=>"This email address is being protected from spambots. You need JavaScript enabled to view it.,This email address is being protected from spambots. You need JavaScript enabled to view it.");

...

...

$rs = $mail->send($recipients, $headers, $body);

 

Also, you can include attachments easily.

 

$file = "/yourfilepath/filename.ext";

...

...

...

$message->setTXTBody($bodyText);

$message->addAttachment($file);

$body = $message->get();

 

But if you're really going to use this script to send email from your IBM I, you'll need to write a program that executes the script using the PHP command line interface (PHP-CLI). This done using QSH (refer to "TechTip: Use PHP and Zend_Mail to Send Email"  for an example). You'll also probably want to add some parameters so you can send generic emails. Parameters to pass might include a list of recipients, a Subject line, body text, a list of email addresses to CC, and a list of files to attach. Good luck. Now…you've got mail. 

 

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: