AS3Mailer – Send email from Flash!

Posted 7 June 2011 by

AS3Mailer is an open source library that allows to easily send emails from Flash using a server script or mailto link. Some of you might remember me posting this a while back and then quickly removed it. Well, yes I did to that, reason being that it needed more security. The new security implementation will prevent anyone from using your mail script, while only requiring minimal “work” from you. Let’s jump in:

Current Server Implementations:

Public API:

On construction of an AS3Mailer instance you can pass two parameters:

  • secretWord – Used for security, see security section below.
  • scriptURL – URL to your script location.

Note: If scriptURL is not set, AS3Mailer will invoke a mailto link instead of calling a server path. This mailto link will include all your values passed/set.

The following public variables are available:

  • from – The sender’s email address.
  • subject
  • messagemessageURL will be ignored if message is set.
  • messageURL – Flash or server loads the message body before sending email or invoking mailto link.
  • mimeVersion – Default is “1.0″.
  • type“text/html” or “text/plain”. These are available as public static constants e.g. AS3Mailer.TEXT_HTML.
  • charsetdefault “utf-8″.
  • scriptURL – Can be set via public property or constructor.

The follow public functions are available:

  • setFrom(address : String, name : String = null) : void – Sets the from address, but nicely formatted e.g. “Name <name@domain.com>”.
  • addRecipient(address : String, name : String = null, type : String = “to”) : int – Adds an email recipient using the same functionality of nicely formatting the address (just like the from address), also you can choose to which “recipient list” you want to add. Your options are: “to”, “cc” and “bcc”. These are also available as public static constants. This function also returns an integer, which is the index of the recipient in it’s respected list, useful if you intend to remove recipients later.
  • removeRecipientAt(index : int, type : String = “to”) : String – Remove and return a recipient at a specific index.
  • clearRecipients(type : String = “all”) : void – Clears an entire list of recipients or all recipients lists. Parameter options are the same as adding, but with the addition of “all”.
  • send(from : String = null, to : String = null, subject : String = null, message : String = null) : void – Does exactly what it says, parameter values passed here will overwrite any set directly with their corresponding public variables.
  • getFullAddress(address : String, name : String = null, braces : String = “<>”) : String – Helper function, just return a nicely formatted email address.
  • isValidEmail(address : String) : Boolean – Helper function, validates an email address. Note: AS3Mailer does not validate any address passed, you need to validate before hand.
  • getRecipientList(type : String) : Array – Returns the Array containing added recipients. Options are the same as when adding. Note: Modifying the Array will affect AS3Mailer.

Security System:

I’ve put together quite a simple little system, but this will spam bots from using your script maliciously. Parts of the information passed the server and your secretWord are added together in a certain way then SHA1′d and added to the request. The server script then then does exactly the same and compares the two, if the two match the request is validated and continues, if not the request is aborted. In this manner there is no need to protect your script behind a htaccess file or anything to the like, but if you want to make double sure, go for it.

Once you downloaded the distribution bundle, modify your server script by replacing the place-holder “%%–REPLACE_SECRET_WORD–%%” with your own secretWord. (PHP taken as an example as there are no other implementations yet!)

function securityCheck() {
    $firstToSplit = explode(",", getValue('to'));
    $toSplit = explode("@", $firstToSplit[0]);
    $firstHalf = strtolower(strrev($toSplit[1]));
    $secondHalf = strtoupper($toSplit[0]);
    $saltedKey = $firstHalf . "%%--REPLACE_SECRET_WORD--%%" . $secondHalf;
    $generatedDigest = sha1($saltedKey);

    return ($_REQUEST['digest'] == $generatedDigest);
}

Once you’ve done this you are ready to move back to AS3 (yeay!). When you construct an instance of AS3Mailer, make sure to pass in your secret word that matched the PHP’s one exactly. Also do not expose your secret word in any way! e.g. Loading a config XML file containing it (or any external file) or flashvars – right out! Don’t do it! Rather “hard code” it into the flash, then the only that someone can get the secret word is by hacking your server or decompiling your flash. But really, who is going to go through all that trouble just for a mailing script?

var mailer : AS3Mailer = new AS3Mailer("%%--REPLACE_SECRET_WORD--%%", "http://somedomain.com/mail.php");

If you intend to upload now, don’t! Read the next part first. We’re done with PHP side of things after that, promise!

Locking Values on the Server:

Part of the security systems is the ability to “lock” values. What I mean by locking is that the server script ignores values from the request and uses the manually set ones. Open PHP file again and scroll down to this part:

$LOCKED = array();
//$LOCKED['from'] = "";
//$LOCKED['to'] = "";
//$LOCKED['subject'] = "";
//$LOCKED['type'] = "";
//$LOCKED['mimeVersion'] = "";
//$LOCKED['cc'] = "";
//$LOCKED['bcc'] = "";
//$LOCKED['charset'] = "";
//$LOCKED['message'] = "";
//$LOCKED['messageURL'] = "";

This is how it looks at default, all you need to do is uncomment the parameter you want to lock and set the value. The script will then ignore the matching parameter coming from the request. E.g. For the example running on this page, I’ve locked the ‘from’ and ‘messageURL’ parameters.

The parameters ‘to’, ‘cc’ and ‘bcc’ are formatted in the same way the flash formats it. E.g.

$LOCKED['to'] = "Someone <someone@somewhere.com>, Any Body <anybody@anywhere.com>";
$LOCKED['cc'] = "copyme@thirdwheel.com";

Note: Comma separated email address with or without nice formatting.

Security Precautions:

If you are using your server to send emails, it is highly advised to lock the message and/or messageURL as this will prevent spam bots from injecting their message into your script. That’s if they managed to get your secret word.

Sample Usage:

Upload to your server and continue with your AS3 sweetness!

This sends an email by not passing any parameters through the send function and also loads the message body from an external html page. Note: The server will load the html page as the client computer doesn’t need to.

var mailer : AS3Mailer = new AS3Mailer("SECRET_WORD", "http://somedomain.com/mail.php");
mailer.setFrom("no-reply@doesflash.com", "Does Flash?");
mailer.addRecipient("some@dude.com", "Some Dude");
mailer.addRecipient("other@dude.com", "Other Dude", AS3Mailer.CC);
mailer.subject = "Test Mail using AS3Mailer";
mailer.messageURL = "http://somedomain.com/static-mail-example.html?";
mailer.send();

This sends an email by passing all values through the send function, including the message body.

var mailer : AS3Mailer = new AS3Mailer("SECRET_WORD", "http://somedomain.com/mail.php");
mailer.send("from@somewhere.com", "to@somewhere.com", "Dear Mr. To", "Hello Mr. To, how are you?");

This will invoke a mailto link as no scriptURL is specified.

var mailer : AS3Mailer = new AS3Mailer();
mailer.send("from@somewhere.com", "to@somewhere.com", "Dear Mr. To", "Hello Mr. To, how are you?");

Sample Application:

This was built with Flex 4.1 using FDT4. Source to this file is included in the distribution bundle, in fact everything is there. :) Update: Script has been removed due to lots of people simply pressing send on the test email address.

Conclusion:

Hope you enjoy using AS3Mailer! Here are some useful links:

As always, feel free to express your concerns or anything related! Thanks for reading! :)

Post Details

  • Darkroom

    good stuff!  thanks much!

    • http://doesflash.com Matan Uberstein

      Glad you like! Thanks for commenting! :)

  • http://doesflash.com Matan Uberstein

    Firstly, thank for showing concern, but the real threat is bot looking for open scripts, in which case a spam bot won’t decompile the flash, nor will it find the secret word in the flash. So your argument is invalid, you can’t say that this is as insecure as last time.

    To crack this script a person (aka a human) is required, and seriously, who the hell in their right mind will spend all that time and effort to get a simple mailing script.

    I’ll let you know once someone has cracked my security word, also I’ll know if it’s you, so don’t even try, unless you want to, in which case I’ll just block your ip from the server and change the security word.

    With Love,
    Matan.

    • http://doesflash.com Matan Uberstein

      I was busy on the phone, so the quickest solution was just to delete it, I’ve put it back.

    • http://doesflash.com Matan Uberstein

      I understand your point, no need get all aggressive about it, all I’m trying to do is make something useful for the community. I’ve locked my message and updated the post.

  • http://doesflash.com Matan Uberstein

    It is up to the user to decide what they want locked and what not, at default everything is unlocked, because that’s the functionality AS3Mailer provides. So if the user wants to lesson the function they can do that systematically by uncommenting what they’ll like to lock.

  • Gadive

    Can you explain how to import your code into Flash CS4? I have tried everything I know and cannot get it to compile. Thanks

    • http://doesflash.com Matan Uberstein

      Hi Gadive,

      1. Download the distribution bundle and extract the contents.
      2. Copy the AS3Mailer .SWC file somewhere your fla can access it e.g. next to the .fla in a libs folder.
      3. In your .fla click -> File -> Publish Settings, click on the Flash tab then the Settings button next to the Script: drop down box. Click on the Library path tab and then the “browse for swc” button (Looks like a little icon of the swf file). Now select the AS3Mailer .swc. You should now be able to compile.
      4. Modify your mail.php with your custom secret word and lock what ever values you want to lock.
      5. FTP you mail script onto your server.
      6. Construct AS3Mailer with the URL to your script.

      PS: You can exchange step three by simple copying the source of AS3Mailer (the “src/com” folder) into your source folder.

      Hope that helps! :)

      • Gadive

        Thanks Matan, it works now. I did not understand Adobe’s documentation.

        • http://doesflash.com Matan Uberstein

          My pleasure :) I’ll be happy to help out with any other queries relating to Flash in general. You can always post general questions on my forum. http://forum.doesflash.com/

  • Bams

    Hi Matan !

    First, sorry for my bad english but i am french!

    Second, thank you so much for sharing your amazing knowledge..
    am always surprised to see people doing that FOR FREE

    Third, i have a problem!
    I read 10 times your introduction and even followed the advices you gave to Gadive but I’m stuck!

    my .fla traces :
    error #2044 : error non pris en charge (“non pris en charge” means : not supported)
    /**

    * Standard PHP mailer.

    * Built for AS3Mailer.

    *

    * NOTE:

    * All arguments can be passed via post data or url variables.

    Do you have an idea of what i’m doing wrong?!

    cheers,
    Sébastien

    • http://doesflash.com Matan Uberstein

      Hi there! Thanks for the kind words and sorry for the late response.

      Error #2044 is a security error, so there are a few things that we can check.

      1. Is the php script on a php server and is the php being executed by the server?
      2. Is the url to the script correct?
      2. Make sure the crossdomain.xml allows cross domain communication if it needs to communicate across multiple domains.

      Let me know if any of the above helps, if not, post a detailed explanation of your problem on my forum: http://forum.doesflash.com/

      Thanks!

  • Alex T

     Hi,

    Using CS5, and Action Script 3.0. I have the SWC file added to the Library, and the code in my script. Compiling my project, it gives the an error:

    “Scene 1, Layer ‘Main’, Frame 100, Line 290    1046: Type was not found or was not a compile-time constant: AS3Mailer.” Even though the SWC is in the library, it can not detect the class. (I have the screenshot attached)

    I tried it as ” simple copying the source of AS3Mailer” solution too, but then I will get this error:

    “D:Users_DocumentsFlashAS3Mailer.as, Line 1    5001: The name of package ‘com.doesflash.mail’ does not reflect the location of this file. Please change the package definition’s name inside this file, or move the file. D:Users_DocumentsFlashAS3Mailer.as”

    Could you help me to fix this, please.
    Alex T.

    • http://doesflash.com Matan Uberstein

       Hi there Alex, are you doing the import statement? E.g. import com.doesflash.mail.AS3Mailer

      If you want to use any external library’s source code, you need to make sure that the folder structure matches the package. So, copy the contents of AS3Mailers’s source folder ( https://github.com/Matan/AS3Mailer/tree/master/src ) into your projects source path. At default this is the same folder as the .fla file.

      Let me know if that helps? Otherwise let’s debug. :)

  • vinod danims

    Good stuff keep it up,

    How to send image to mail with as3mailer? and what is the contentType?

  • James_sager_PA

    Thank you very much.  I am writing a custom server and I need this.

  • Filzah90

    Sip mas

  • http://twitter.com/pink2graphy lorimar

    Hi, I would like to know if I can attach file here. I will be creating a Custom Jersey design software and that’s the idea, sending the created design to email.

    • http://doesflash.com Matan Uberstein

      Hi, you can’t attach files with this mailing script. I’d suggest using something better suited to what you’re looking for. I wouldn’t recommend this simple script heavy mail use. Your application’s backbone should run a well supported framework like CodeIgniter where you can write a restful API to send out emails with attachments, etc.

      • http://www.facebook.com/profile.php?id=1082654669 Lorimar Sto Tomas Magtoto

        Thanks!