Friday, January 7, 2011

Sending an email from your Flex app just got easier (short post)

I want to send an email from my Flex app.  Well, if I don't have a backend mailserver setup, and I want my user to send me a message about, say, the app's service crashing, the easiest way to do this is through URLRequest!

Quick demonstration - 

1) Create the url request: 

var u:URLRequest = new URLRequest("mailto:"+EMAIL_ADDRESS);

2) Create a variable for the subject and body:

var v:URLVariables = new URLVariables(); //interestingly, you can put all the variables into a string and pass that in, but here we're just going to append them as properties to the object

3) Assign those properties:

v.subject = "Application crashed";
v.body = TEXT_OF_CRASH_MESSAGE;

4) Pass those variable properties into the URLRequest:

u.data = v;

5) Navigate to the URL:

navigateToURL(u, "_self"); //the _self is .js and not required

This is an easy way to pass any valuable info from your flex app into your user's default email program (Entourage/Outlook, Thunderbird, Mail, etc.)

14 comments:

  1. What if my app wants to send the message directly and not use the default email program?

    ReplyDelete
    Replies
    1. Try this from Thibault Imbert. It's a bit dated, but might work: http://www.bytearray.org/?p=27

      Delete
  2. Replies
    1. You might get into some trouble with HTML text, but you could try to encode it via CDATA? Otherwise, escape the characters, i.e. &lta href=google.com /&gt>.

      Not sure if that helps, but maybe give it a shot?

      Delete
  3. Hello. This is very useful, thank you. My only question is how do you format the v.body? I get some input from the user and want to pass it all the the body of the message but in a formatted way:
    First name: ______
    Last name: _______
    Message: _________
    Is there any way to achieve something similar to this?
    Many thanks

    ReplyDelete
    Replies
    1. Never mind that, I found it! "\n" does the trick quite nicely.
      Thanks again

      Delete
    2. Glad you found an answer before I could respond. Thanks for sharing!

      Delete
  4. Nice! It works....but how to set the attachment file to the mail?

    ReplyDelete
  5. Very helpful post!

    ReplyDelete
  6. What if I want that email to composed with attachment?

    ReplyDelete
  7. Maybe try this:

    var urlVariables:URLVariables = new URLVariables();
    urlVariables.attachment = myAttachment

    ReplyDelete
    Replies
    1. i think navigate to url doesn't attach any attachments. what are the other ways we can do it?

      Delete
  8. How can we attach an image with body text?

    ReplyDelete
  9. Excellent solution! Is there anyway to send email using the native program without prompt to send (Auto-send)?

    ReplyDelete