How to Improve Design for HTML, Plain Text and Multiple Recipients?

Hello there,
JavaMail programming is so fun! I first start off mixing the JavaMail code inside a servlet and then refactored it to two separate classes.
Mailer is the independent class which uses JNDI to look up config parameters, sends e-mails, and then closes the connection with the protocol.
public class Mailer {
     private Session mailSession;
     protected void sendMsg(String email, String subject, String body)
     throws MessagingException, NamingException {
          Properties props = new Properties();
          InitialContext ictx = new InitialContext(props);
          Session mailSession = (Session) ictx.lookup("java:/Mail");
          String username = (String) props.get("mail.smtps.user");
          String password = (String) props.get("mail.smtps.password");
          MimeMessage message = new MimeMessage(mailSession);
          message.setSubject(subject);
          message.setRecipients(javax.mail.Message.RecipientType.TO,
                    javax.mail.internet.InternetAddress.parse(email, false));
          message.setText(body);
          message.saveChanges();
          Transport transport = mailSession.getTransport("smtps");
          try {
               transport.connect(username, password);
               transport.sendMessage(message, message.getAllRecipients());
               Logger.getLogger(this.getClass()).warn("Message sent");
          finally {
               transport.close();
}MailController is just a simple Java servlet where a Mailer object is instantiated and a String is passed inside the Mailer.sendMsg() method.
public class MailController extends HttpServlet {
     /** static final HTML setting for content type */
     private static final String HTML = "text/html";
     myapp/** static final HTML setting for content type */
     private static final String PLAIN = "text/plain";
     public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
          doPost(request, response);
     public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
          response.setContentType(PLAIN);
          PrintWriter out = response.getWriter();
          String mailToken = TokenUtil.getEncryptedKey();
          String body = "Hello there, " + "\n\n"
                    + "Wanna play a game of golf?" + "\n\n"
                 + "Please confirm: https://localhost:8443/myapp/confirm?token="
                 + mailToken + "\n\n" + "-Golf USA";
          Mailer mailer = new Mailer();
          try {
               mailer.sendMsg("[email protected]", "Golf Invitation!", body);
               out.println("Message Sent");
          catch (MessagingException e) {
               e.printStackTrace();
          catch (NamingException e) {
               e.printStackTrace();
}Have some design issues...
If you can notice, I manually place the body of the e-mail (as a String) from inside the client (in this case, a Java Servlet). Also, I manually have to switch the content type inside the doPost().
Question(s):
(1) How can the Mailer class be set up, so it can send both HTML and plain text messages?
(2) How can the Mailer class be structured to send e-mail to multiple recipients or one user?
(3) Would both of these features / actions require writing two overloaded methods for sendMsg()?
Would appreciate it if someone could help me...
Happy programming,
Michael

Okay, I came up with this single method:
Mailer.java:
public class Mailer
     private Session mailSession;
     protected void sendMessage(String email, String recipient, String subject,
               String plainText, String htmlText)
        throws MessagingException, NamingException
          Properties props = new Properties();
          InitialContext ictx = new InitialContext(props);
          Session mailSession = (Session) ictx.lookup("java:/Mail");
          String username = (String) props.get("mail.smtps.user");
          String password = (String) props.get("mail.smtps.password");
          MimeMessage message = new MimeMessage(mailSession);
          InternetAddress from = new InternetAddress(email);
          InternetAddress to = new InternetAddress(recipient);
          message.setSubject(subject);
          message.setFrom(from);
          message.addRecipient(Message.RecipientType.TO, to);
          Multipart multipart = new MimeMultipart();
          BodyPart messageBodyPart = new MimeBodyPart();
          messageBodyPart.setText(plainText);
          multipart.addBodyPart(messageBodyPart);
          messageBodyPart = new MimeBodyPart();
          messageBodyPart.setContent(htmlText, "text/html");
          multipart.addBodyPart(messageBodyPart);
          message.setContent(multipart);
          Transport transport = mailSession.getTransport("smtps");
          try {
               transport.connect(username, password);
               transport.sendMessage(message, message.getAllRecipients());
               Logger.getLogger(this.getClass()).info("Message sent");
          catch (Throwable t) {
               Logger.getLogger(this.getClass()).error("Unable to Send Message");
               t.printStackTrace();
          finally {
               transport.close();
}Created a MailController class to instantiate and run the Mailer class.
public class MailController extends HttpServlet {
     // doPost() method()
     public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
          response.setContentType(PLAIN);
          PrintWriter out = response.getWriter();
          String mailToken = TokenUtil.getEncryptedKey();
          String plainText = "Hello there, " + "\n\n"
                    + "I wanna invite you to a game of golf!" + "\n\n"
     + "Please confirm: https://localhost:8443/myapp/confirm?token="
                    + mailToken + "\n\n" + "-Golf USA";
          String htmlText = "<H1>Golfer Challenge!</H1>";
          Mailer mailer = new Mailer();
          try {
               String from = "[email protected]";
               String recipient = "[email protected]";
               String subject = "Golf Challenge";
               mailer.sendMessage(from, recipient, subject, plainText, htmlText);
               Logger.getLogger(
                           this.getClass()).info("Message Sent to: " + recipient
                                                          + " from: " + email);
               out.println("Message Sent to: " +
                                         recipient + "\n" + " from: " + email);
          catch (MessagingException e) {
               e.printStackTrace();
          catch (NamingException e) {
               e.printStackTrace();
}Question(s):
(1) How come the Multipart Alternative only supports HTML for the second part? Can I specify it to send HTML first and plainText second?
(2) How would I send in multiple recipients? Would I have to pass in an array reference (surrounded by a for loop) inside sendMessage() as follows:
mailer.sendMessage(from, myArray, subject, plainText, htmlText);
Thank you for all of your help!
-Michael                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • How to send a plain text and HTML email at once?

    Hi all,
    I'm attempting to use cfmailpart to send a HTML and plain text email all in the same cfmail script.  I'm using Outlook and Gmail to test.  I temporarily changed my Outlook settings to "read all standard mail in plain text," but it does not read the plain text cfmailpart of the email, it just attempts to format the text from the HTML email and display the links.  If I remove the HTML cfmailpart from my cfmail script, the plain text version is delivered, but Outlook removes extra line breaks that I actually want to keep intact, and some of the other formatting is improperly rendered.  Is there a better way to make sure email clients hold the plain text formatting (even though there really isn't any formatting with plain text) and a better way to test?  The HTML version looks great in both Gmail and Outlook.
    Thanks!

    Use the wraptext attribute of the cfmailpart tag to add line breaks.

  • I have no volume for incoming calls ,texts and emails how do i fix it

    I have no volume alert for incoming calls ,texts and emails  . How can I fix this as I can watch video clips wiyh sound

    Hello Strangers1,
    After reviewing your post, I have located an article that can help in this situation. It contains a number of troubleshooting steps and helpful advice concerning audio issues:
    iPhone: No sound or distorted sound from speaker
    http://support.apple.com/kb/ts5180
    Verify that the volume is set to a level you would normally be able to hear.
    Ensure that there is nothing plugged in to the headset jack or the dock connector.
    If the iPhone is in a protective case, make sure that the speaker port isn't blocked by the case.
    Make sure that the speaker and dock port aren't clogged with debris. If necessary, clean it with a clean, small, dry, soft-bristled brush. Carefully and gently brush away any debris.
    If an audio issue occurs when using a specific application, try testing other applications to see if the issue persists.
    If the iPhone is paired with a Bluetooth headset or car kit:
    Try turning off Bluetooth.
    If you experience difficulties with the Bluetooth feature, follow these troubleshooting steps.
    Restart the iPhone.
    If restarting doesn't fix the issue, ensure that your iPhone is updated to the latest version of iOS.
    If the issue is not resolved, please contact Apple Support.
    Learn more about troubleshooting iPhone hardware issues.
    Thank you for contributing to Apple Support Communities.
    Cheers,
    BobbyD

  • Plain text and attachment in Mail Adapter (Receiver)

    Hello,
    we have to generate a mail in the mail-adapter with a specific text and an attachment.
    The attachment is a document in pdf-format, that is generated inside an adapter-module out of the payload-document.
    An additional text has to be added to the mail for the receiver in plain-text-format, like "Dear customer ... enclosed you will find ...".
    Is it possible to mix plain-text and attachments in the mail adapter? Does anybody know how we can do that?
    Regards,
    Thorsten

    Hi,
    yes you can do it very easily inside the adapter module
    if you're already using the adapter module then
    you can just enhance it a little bit
    you can add the pdf to the attachment section and
    leave dear customer in the standard payload
    you can even make it a little bit more dynamic
    and create a module that will take the input from
    the communication channel config (modules tab) - for example xml tag name in which you will specify
    the dear customer (or any other text) and after this
    the pdf creating can use the xml without this tag...
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions">XI FAQ - Frequently Asked Questions</a>

  • My daughter is going to Canada for a week and i would like to know if it will cost extra for her to text and/or call someone in the United States?

    My daughter is going to Canada for a week and i would like to know if it will cost extra for her to text and/or call someone in the United States?

    http://businessportals.verizonwireless.com/international/traveling_to/North_America/Canada.html
    69 cents a minute for calls, texts covered under an existing texting plan or the standard pay per text rate if you don't have one.
    If you're traveling in Canada, contact Customer Service at 800-922-0204 from any landline phone.
    Global Picture and Video Messages are billed at the same per-message rate as though they were sent from the U.S. Accordingly, you can send/receive Picture and Video Messages with customers of:
    Verizon Wireless (domestic rates/bundles apply)
    Other domestic carriers (domestic rates/bundles apply)
    Canadian, Mexican and Puerto Rican carriers (domestic rates/bundles apply)
    Select International carriers (global rates apply) 
    When sending or receiving there's an additional data transport charge billed at the destination's Data Pay per Use Rate multiplied by the size of the Picture or Video, which can vary greatly.
    A data network is required to send picture or video outside the U.S. See the Data Roaming List for eligible destinations.
    Attempts to send Pictures or Videos are charged, even if the delivery fails.
    Text Messages sent or received while in Canada, Puerto Rico and the U.S. Virgin Islands are billed as though you were in the U.S.
    Check out our Nationwide plus Canada plans if you frequently call or travel to Canada.

  • How to get classification for a given material and material type in MM

    Hello Friends,
    One of my developer colleagues is struggling to find out : how to get classification for a given material and material type in MM?
    He is looking for probable table and table fields to Select from.
    I would appreciate seriously any help in this regard.
    ~Yours Sincerely

    Hi
    Below given the flow and table details for a given class and class type.
    - Table KLAH --> This contains the "Internal class no" [ for the given Class & Class type ]
    - Table KSML --> This contains the " internal character numbers " [ nothing but characteristics attached to the class ] , which can be fetched with the above fetched internal class no
    - Table AUSP --> This table contains the objects ( material ) attached to the internal characters of that class
    - Table CABNT --> This table contains the "Description" for the internal character numbers.
    - award points if this is ok

  • How to set password for a zip file and should be checked when reading that

    Hi friends,
    how to set password for a zip file and should be checked when reading that file???
    thanks.
    Praveen Reddy.J

    Heyy man, i think, u did not get my problem.
    all i have to do is:
    i have to create a zip file, and we should secure it with password when creating. and whenever the user wants to open that zip file he should provide correct passowrd otherwise he could not read that file. So, we should check for that also.
    Tanks for reply.

  • When I send an email from Apple mail, it send inbedded links, not embedded, my font shows as plain text and signature sends as attachment??

    When I send an email from Apple mail, it send inbedded links, not embedded, my font shows as plain text and signature sends as attachment??

    inbedded is not a word.

  • If I get the iphone 5 with plan and contract with 2 years or 3 can i pay $25 each mouth for just ulimited texting and 250 min of talking.

    If I get the iphone 5 with plan and contract with 2 years or 3 can i pay $25 each mouth for just ulimited texting and 250 min of talking.

    Ask the carrier instead of making yourself look like a fool by posting such a question in a user to user technical support forum.

  • How can I combine a lot of text and images on the same screen?

    How can I combine a lot of text and images on the same screen?  I can get a couple of words on the screen with a graphic but not 10 lines.  I need 10 lines on the page with the image. 

    Priscilla,
    I routinely combine 10 lines of 36 pt bible or lecture text to a suitable background using Boris Title 3D.
    Many times the text is too long to fit the screen using Boris, so I devide it into 2 or more parts with no transition between sections.
    In my case, the text is on the screen as the speaker quotes them.
    David

  • How can I erase the residual background text and images from the backside of a scanned page?

    How can I erase the residual background text and images from the backside of a scanned page?
    Also, I wanted to know what each subscriptions included as far as my question above is concerned?
    I am trying to edit a scanned page (pdf file) by changing some words and erasing the background from the page that is showing through it since the paper is so thin and want to know which subscription to buy in order to complete these tasks?

    This cannot be done in Reader. I think you will need software like Photoshop. You may be able to get buy with Photoshop Elements, but I haven't used recent versions of that software. Using either software this will not be an automated task.

  • How do I set up a plain, text only document?

    I've been using TextEdit for all my word processing for the past several years. Now, I'd like to use iWork 09
    but for the life of me can't figure out how to do a PLAIN old text document. The margin markers won' move outside
    of the  1" pre-set border the blank page opens in default.  Text boxes show up even though I've selected "blank page".
    I just want to write a personal journal. I want to start at the upper right of the page and write until I'm done.
    Flowing from one page to the next automatically with approx. 1/2" side margins and maybe 1/2- 1" top and bottom. 
    Everything's so complicated now in comparison to the old Apple Works programs--from a number of  years ago.  
    I understand for those who use it for other things such a letters,  newsletters,  pamphlets, flyers, any number of
    business functions this is probably all very helpful and efficient, but for plain old unformatted text so far it's
    been a pain in the ___! 
    Why isn't a blank page BLANK?  When I open TextEdit  a new text page is blank with nothing preset.
    No text boxes to monkey with or try to get rid of. I can set margins anywhere I want-- no hassle.
    I can write until I want to stop. I don't need to figure out how to get it go on to a second page.
    I suppose I could just keep using TexEdit but I've had this program for a couple yrs. and up until today have
    only used "Numbers".  It would be nice to be able to use the word processing as well.  I expected Numbers
    to be a bit confusing to learn how to use it again for spread sheets but so far no problems there. 
    Word processing, especially simple word processing, on the other hand, I expected to be a snap and it
    has me very frustrated!  Go figure!
    Would someone please explain to me how to get a plain, blank, no text boxed, no pre-set margin, open-ended
    for  1 > infinity number of pages, completely unformatted word processing page(s) opened and ready to use?
    Also, can I  or  how can I make it a custom/user defined  "template" (?), or standard default set-up, so I don't
    have to mess with anything everytime I want this type of page?
    Thank you.

    Simple, keep using TextEdit.
    Pages is not a text editor which is what you are asking for. It is a Word Processor/DTP/Spreadsheet/Graphing application.
    Don't undersatnd why you are rushing to put all your eggs into one proprietry, single platform, unique format that Apple will ultimately abandon.
    If you want more than you are getting from TextEdit, try iText Express (free).
    Peter

  • What is the content type for a plain text document.

    Hello :)
    I want to generate a plain text document for the user to either see, or to save to disk directly. What do I out for the setContentType MIME type for this?
    Thanks
    Jeff.

    text/plain
    zakir

  • Importing from Eudora problems - html messages being displayed in plain text and problems with attachments

    Hello,
    I hope you can help me. I've imported all my emails from Eudora into Outlook 2010 but I have a couple of problems.
    All emails that I've imported which had attachments with them have a notice on them saying the attachment has been blocked. I can always browse to the folder whereb my old attachments are stored, but this is still inconvenient.
    Secondly, all my messages that I've sent in the past (html) are being displayed in plain text, which is making them difficult to read because of all the html tags being displayed.
    Also with emails that I've sent in the past- there is no record of any attachments being sent with messages which I know had attachments with them.
    Any ideas? I've trawled google and had no luck except finding programs that cost $70 that can import everything properly.
    David

    David:
    I know this is a very old thread, but did you every figure out a way to fix the formatting of imported Eudora mail?
    I just "upgraded" from Eudora to Outlook 2010 ...
    and have 10 years worth of HTML formatted e-mail that now shows up as plain text with embedded html formatting ...
    apparently it is a long-running problem that has roots in the way Eudora formats messages ...
    Outlook and other e-mail clients all seems to have issues with importing and do not properly recognize HTML-formatted messages from Eudora ... very sad that I can no longer really "read" my old e-mail at this point ...  :-(
    See closing paragraphs here:   http://its.uiowa.edu/support/article/2800
    Same problem over at Mozilla going back 10+ years ... not sure if they fixed it..........
    https://bugzilla.mozilla.org/show_bug.cgi?id=3157

  • How to improve performance for Custom Extractor in BI..

    HI all,
               I am new to BI and started working on BI for couple of weeks.. I created a Custom Extractor(Data View) in the Source system and when i pull data takes lot of time.. Can any one respond to this, suggesting how to improve the performance of my custom Extractor.. Please do the needfull..
      Thanks and Regards,
    Venugopal..

    Dear Venugopal,
    use transaction ST05 to check if your SQL statements are optimal and that you do not have redundant database calls. You should use as much as possible "bulking", which means to fetch the required data with one request to database and not with multiple requests to database.
    Use transaction SE30 to check if you are wasting time in loops and if yes, optimize the algorithm.
    Best Regards,
    Sylvia

Maybe you are looking for