Sending chinese HTML with javamail - is there no definitive answer ?

I'm using the following code to send a HTML and text e-mail
(text for people with HTML-challenged email clients). I sent
2 emails to 2 email addresses which reside on the same server
- eg. [email protected] and [email protected] - and read the
emails with the same e-mail client (Eudora) on the same PC.
The HTML and Chinese displays perfectly when it's sent to one
of the email addresses ([email protected]) but the HTML and
Chinese are always corrupt when I send them to the other.
This is a repeatable error and it has me completely stumped.
     // Example Initial values (drawn from a database) :
     String smtpHost = "mail.mydomain.com";
     String sender = "[email protected]";
     String subject = "Give me strength.... ";
     InternetAddress sender = new InternetAddress("[email protected]");
     InternetAddress receiver = new InternetAddress("[email protected]");
     String txtMsg = "a long text message blah...";
     String htmlMsg = "<h1>Wooo</h1><img src='http://mydomain.com/blink.gif'>";
     String language = "zh-tw" // can also be "en-us" or "zh-cn"
     // CREATE MAIL MESSAGE & HEADERS
     Properties props = System.getProperties();
     props.put("mail.smtp.host", smtpHost);
     Session session = Session.getDefaultInstance(props, null);
     Message msg = new MimeMessage(session);
     msg.setFrom(sender);
     msg.addRecipient(Message.RecipientType.TO, receiver);
     msg.setSubject(subject);
     msg.setSentDate(new Date());
     msg.setHeader("Mime-Version" , "1.0" );
     msg.setHeader("Content-Transfer-Encoding", "quoted-printable");
     // MESSAGE BODY - TEXT & HTML
     MimeMultipart mimeAllContent = new MimeMultipart("alternative");
     MimeBodyPart mimeText = new MimeBodyPart();
     MimeBodyPart mimeHtml = new MimeBodyPart();
     mimeText.setText(textMsg);
     mimeText.setHeader("Mime-Version" , "1.0" );
     mimeText.setHeader("Content-Type" , "text/plain");
     mimeText.addHeader("Content-Type", "charset=UTF-8");
     if (!language.equals("")) {
          mimeText.setHeader("Content-Language", language);
     mimeText.setHeader("Content-Transfer-Encoding", "quoted-printable");
     mimeHtml.setContent(htmlMsg, "text/html");
     mimeHtml.setHeader("Mime-Version" , "1.0" );
     mimeHtml.setHeader("Content-Type" , "text/html");
     mimeHtml.addHeader("Content-Type", "charset=UTF-8");
     if (!language.equals("")) {
          mimeHtml.setHeader("Content-Language", language);
     mimeHtml.setHeader("Content-Transfer-Encoding", "quoted-printable");
     mimeAllContent.addBodyPart(mimeText);
     mimeAllContent.addBodyPart(mimeHtml);
     msg.setContent(mimeAllContent);
     msg.setHeader("Content-Type" , mimeAllContent.getContentType());
     // SEND THE MESSAGE
     msg.saveChanges();
     Transport.send(msg);
     return true;
Let me repeat - Using the code below, a HTML & Text ("Alternative"
MimeMultiPart) message is sent, and arrives at the recipient's
mailbox. When it is sent to one user ([email protected]), it never
renders properly. When it is sent to another ([email protected]), it's
OK. The destination server, email client, PC are the same in both
cases and the only variable is the recipient's email address.
How can this be ?
I think I've gone overboard by setting the Content-Transfer-Encoding
for both the HTML and Text MimeParts as well as the actual Message.
Could somebody please confirm which parts I should set the Content-
-Language, Content-Transfer-Encoding and Content-Type b/c I'm
going in circles at the moment.
Thanks indeed, to anybody who has experience sending doublebyte
with Javamail and can help me clear this up once and for all.
I find it incredible that after 3 years, there is still no
definitive answer to accomplishing this, and it remains an
elusive black art.
Regards,
chas
ps. The data being sent is in MySQL not that that matters at all.

Try adding code to validate submitted email addresses before they go into your database.
String emailAddress = (from where ever)
if(emailAddress != null) emailAddress = emailAddress.trim();
if(emailAddress == null) // skip this address
// I also check for a list of illegal internet email address characters, as I think the email addresses allowed by Javamail are too lenient.

Similar Messages

  • How to send a message with javamail api

    Hi, anybody can tell me how i do to send a message with javamail?
    Thanks.
    Daniele.

    [rossifumi80],
    Here's a simple JavaMail application SendMessage.java that will connect a SMTP host and send a mail message out:
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class SendMessage {
      public static void main (String args[]) throws Exception {
        String host = args[0];
        String from = args[1];
        String to = args[2];
        // Get system properties
        Properties props = System.getProperties();
        // Setup mail server
        props.put("mail.smtp.host", host);
        // Get session
        Session session = Session.getDefaultInstance(props, null);
        // Define message
        MimeMessage message = new MimeMessage(session);
        // Set the from address
        message.setFrom(new InternetAddress(from));
        // Set the to address
        message.addRecipient(Message.RecipientType.TO,
          new InternetAddress(to));
        // Set the subject
        message.setSubject("Hello JavaMail");
        // Set the content
        message.setText("Welcome to JavaMail");
        // Send message
        Transport.send(message);
    }HTH.
    Allen Lai
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • I Can't send a message with JavaMail

    I can't send mail with JavaMail. I Try send a e-mail, for example, to: [email protected], from: [email protected], my smtp: smtp.alunos.ufu.br, but when i try it, i received a message the e-mail [email protected] not in server smtp.alunos.ufu.br.
    I don't anderstend what happen. I need the alunos.ufu.br send my message to [email protected]
    Somebody can help me ?????

    I think the problem is that your smtp server smtp.alunos.ufu.br is not relaying to addresses not local to itself. Please post the exact stack trace. There is some 500 level error being returned by the server that will tell you exactly what is happening.

  • Is there a Definitive Answer? Apple Mobile Device Support won't install

    Firstly apologies, i have lost track of the number of threads i have read on this site, but none seem to resolve the issue. I am running Windows 7 64Bit (Professional), also have the same problem on a XP SP3 laptop... but the works laptop will allow the install, also win7 64 bit (but not alllowable software so need to uninstall)
    I have mangemed to finally install Itunes and all associated software packages to 10.7.21, following months and months of hassle (last working version of itunes was down in 10.1.??)
    BUT, frustratingly i still cannot get Apple mobile Device support to install. Before any one asks the obvious questions i have tried just about everything (assuming the one i havent tried is the one that works)
    I have extracted the install file and ran that seperately, yes as administrator (both right click and forcing the compatibility in the file properties), both accounts on the machine, also created a new account and tried on that. Same issue as most people, failed to install and rolled back
    I have tried installing whilst in compatibilty check and get a report that it is an incompatible application.
    When opening Itunes itself i get a message that i need to install the 64bit version.
    This is starting to get seriosly annoying in that my iphone 4 has now also decided to fail during an update to ios6... serves me right for listening to one of the genius's instore.
    Anybody with any ideas please throw them this way. Next step is to format machine and start from scratch

    So, after another evening of trawling the internet i found the following and decided it was worth a try
    http://randomwindowstips.wordpress.com/2009/12/08/windows-7-itunes-9-software-is -not-installed/
    The following is taken straight from Aurelius, so huge HUGE thanks. (This works if you still have 10.6.3, failing that, if you know anyone that has the latest version, this is how i got this **** programme to actually work (or wait, as this will be updated shortly!!) I had at this point let everything install from Itunes installer and again had the rollback on the AMDS.
    Copy the following folders from a working machine to your machine (apologies if you don't know anyone with a working copy, keep an eye on the link as it will be updated)
    C:\Program Files\Common Files\Apple\Mobile Device Support
    C:\Program Files (x86)\Common Files\Apple\Mobile Device Support
    Next, type regedit into windows search and allow the programme to start. Go to the following address:
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Apple Inc.\Apple Mobile Device Support]
    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Apple Mobile Device]
    Right click and export the files. Next you need to copy them to your machine and double click them and allow to install. Restart and hopefully all is finally well (or it was on mine).
    Good luck to anyone who finds this.

  • How to send an Html File as an Attachment tht has style included?

    Hi Friends,
    If anybody has sample code ...
    please post it here..

    Not sure what you're asking for but have you seen the sendhtml.java
    demo program included with JavaMail?

  • Send Email in HTML Format with Javamail.

    GOD BE BLESSED!
    Hello dudes,
    i create a jsp page let me send emails from a database using the API Javamail.
    But these emails when i send then, goes in text format only, and i want to send emails in HTML format too. Anyone can help me?
    I think the Javamail API can send in HTML format.
    thanks and sorry, my english is basic but i think you understand. ;)
    Adler Medrado

    I was trying to do the same thing...I found this on the java.sun.com website somewhere. Hope it works out for you.
    try {
    String host = "";
    String from = "";
    String to = "";
    String fileAttachment = fileName;
    // Get system properties
    Properties props = new Properties();
    // Setup mail server
    props.put("mail.smtp.host", host);
    // Get session
    Session session1 =
    Session.getInstance(props, null);
    // Define message
    MimeMessage message =
    new MimeMessage(session1);
    message.setFrom(
    new InternetAddress(from));
    message.addRecipient(
    Message.RecipientType.TO,
    new InternetAddress(to));
    message.setSubject("");
    // create the message part
    MimeBodyPart messageBodyPart =
    new MimeBodyPart();
    //fill message
    messageBodyPart.setText("");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
    new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(
    new DataHandler(source));
                   messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);
    // Put parts in message
    message.setContent(multipart);
    // Send the message
    Transport.send( message );
    }catch (Exception e){
    System.err.print("Mailing error:");
    System.err.println(e);

  • Impossible to send a mail with a message in HTML format

    Hi
    I try to send a message in HTML format. Here is the code :
        public void sendMessage(String subject, String message, String to, String cc, String bcc) throws MessagingException  {
             MimeMessage mimeMessage = mailSender.createMimeMessage();
             MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            if(to!=null && !to.equals("")){
                 mimeMessageHelper.setTo(to);
            if(cc!=null && !cc.equals("")){
                 mimeMessageHelper.setCc(cc);
            if(bcc!=null && !bcc.equals("")){
                 mimeMessageHelper.setBcc(bcc);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(message,true);
            mimeMessageHelper.setFrom(from);
            logger.info("host = "+mailSender.getHost());
            logger.info("Port = "+mailSender.getPort());
            //logger.info("UserName = "+mailSender.getUsername());
            //logger.info("Password = "+mailSender.getPassword());
                mailSender.send(mimeMessage);
        }and the message is the following :
    String message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+ "<htmlxmlns=\"http://www.w3.org/1999/xhtml\"><head><head/><body>"
    +messageSource.getMessage("startpeople.messagetosend.part1", null, Locale.ENGLISH)+ user.getFirstName()+" "+ user.getLastName()+",\n"
    + messageSource.getMessage("startpeople.messagetosend.part2", null, Locale.ENGLISH)+"\n"
    + messageSource.getMessage("startpeople.messagetosend.part3", null, Locale.ENGLISH)+ newPassword+"\n"
    + messageSource.getMessage("startpeople.messagetosend.part4", null, Locale.ENGLISH)+"\n"
    + messageSource.getMessage("startpeople.messagetosend.part5", null, Locale.ENGLISH)+"\n"
    + messageSource.getMessage("startpeople.securim.homepage.internet.address", null, Locale.ENGLISH)+"</body></html>";according to what I found on internet, the method MimeMessageHelper.setText(message,true); specifies that the message is sent in HTML format ( second argument is boolean "true" saying it is a HTML message ).
    But I don't get the message in HTML format. Anyone can help me ? thank you in advance

    MimeMessageHelper appears to be a Spring Framework class; better to ask your
    question in their support forum.
    Of course, you don't need to use MimeMessageHelper to create a simple html message,
    and in your case it doesn't seem to be making things any simpler. See the JavaMail FAQ
    and the demo programs included with JavaMail for simple examples of how to create an
    html message.

  • Is there a way to use my branding when sending a file with Adobe Send?

    Is there a way to include my logo in the message with Send files?

    Hi dporterphotography,
    The branding feature isn't available in Send just yet, but it is planned for a future release. In the meantime, you're welcome to send your file, with branding, using Adobe SendNow. You can log in to SendNow at https://sendnow.acrobat.com/signin.html using the same Adobe ID and password that you use for Send.
    Best,
    Sara

  • I have a new iPhone 6 plus and all is OK. But the mail shows more than 400 'unread' messages whereas there are none in the mailbox or trash or anywhere else I have looked. I can send and receive with no problem. I'm sure I have no unread messages.

    I have a new iPhone 6 plus and all is OK. But the mail shows more than 400 'unread' messages whereas there are none in the mailbox or trash or anywhere else I have looked. I can send and receive with no problem. I'm sure I have no unread messages.

        jsavage9621,
    It pains me to hear about your experience with the Home Phone Connect.  This device usually works seamlessly and is a great alternative to a landline phone.  It sounds like we've done our fair share of work on your account here.  I'm going to go ahead and send you a Private Message so that we can access your account and review any open tickets for you.  I look forward to speaking with you.
    TrevorC_VZW
    Follow us on Twitter @VZWSupport

  • Is there a way to send a message with a photo attached using imessages. I am not able to send a photo to one of my contacts because I am sending the contact a message text messages. I don't want to send contacts text messages. I want to send them iMe

    Is there a way to send a message with a photo attached using imessages. I am not able to send a photo to one of my contacts because I am sending the contact a message text messages. I don't want to send contacts text messages. I want to send them iMessages.

    Kolyei, sorry for the late reply.
    Have your brother create a contact in his phone for himself. Inside his own contact, have him add his phone number and his iCloud address.
    Settings > Messages > Send & Receive Have your brother select both his phone number and email addresses where he would like to receive iMessages.

  • When I send an email with Mail, I often confuse the account which I'm using. The result is that I send a message with the wrong account! Is there a way to avoid this (for example a reminder before the email is sent)?

    When I send an email with Mail, I often confuse the account which I'm using. The result is that I send a message with the wrong account! Is there a way to avoid this (for example a reminder before the email is sent)?

    Hi, thanks for the answer, I did that already. Unfortunatly this doesn't help me at all, as I often forget to check the menu. For me composing the message is writing the text, the subject, the person to who is addressed and than press "send".
    I often forget to check the "from", and this is a problem because the software select itself one of the accounts.
    Isn't there a way at least to put as a default a blank field instead of one of the accounts? or an account which doesn't work so if I forget to specify the "from" I will be rnotofied that the message can't be sent.
    I guess this could be a rather common problem for many people!
    Thanks
    Sergio

  • I have a problem with mail.  the spelling and grammer check box before sending the messege is no longer there.  I did everything but cannot get it back.  is ther anyone who knows how to get the box with spelling and grammer checks before sending

    i have a problem with mail.  the spelling and grammer check box before sending the messege is no longer there.  I did everything but cannot get it back.  is ther anyone who knows how to get the box with spelling and grammer checks before sending the mail.
    Also the mail is acting very funny by not getting the rules work in a proper method.  Is ther a software to repair mail.

    i did both of them, but still the while sending the mail the diolog box is not showing up and also the spelling and grammer does not do the spelling check. 
    This problem just started for about 3 to 4 days now.  earlier it was working normally.

  • How to send a message with Send-MailMessage cmdLet powershell exchange which uses a html file as a parameter

    Before the mailboxes migration E2003 toward E2010 SP2, I have to send a mail which body already exists as a html file.
    Here the powershell I currently use :
    import-csv d:\path\TestLot.csv  | foreach {Send-MailMessage -To $_.PrimarySmtpAddress -From
    [email protected] -Subject "Migration " -body "Your mailbox Migration will start in 2 days." -SmtpServer servXXX}
    And it is allright !
    But, I was asked to use an existing html file instead of my poor : -body "Your mailbox Migration will start in 2 days." 
    Does anybody know the way to do this ?
    Thank you for your help
    PATMOY
    BOAT

    Hi,
    I have the html code in a variable so i can personalize the mails:
    $htmlcode = '<html><body style="background:#FFFFFF"><head><title>Activaion email</title></head>'
    $htmlcode += '<style type="text/css">'
    $htmlcode += '#HLine { font-size:20px; font-family:Verdana; font-weight: bold; }'
    $htmlcode += '#txt { font-size:12px; font-family:Verdana;}'
    $htmlcode += '</style>'
    $htmlcode += '<img src="/img/HBPMAN0aGcc.gif" width="52" height="52" />&nbsp;&nbsp;&nbsp;<br />'
    $htmlcode += '<h1 id="HLine">Your BlackBerry account has been created ...</h1>'
    $htmlcode += '<div id="txt"><strong>... Your User Data:</strong><br />'
    $htmlcode += '&nbsp;&nbsp;&nbsp;<br /><table border="0" id="txt"><tr><td>&nbsp;&nbsp;<strong>Username:</strong></td><td>'+$UsrData.Email+'</td></tr>'
    $htmlcode += '<tr><td>&nbsp;&nbsp;<strong>Activation Password:</strong></td><td>'+$UsrData.pass+'</td></tr></table><br />'
    $htmlcode += '<strong>The activation credentials are valid for just 5 days after receipt of this email!</strong><br /><br/ >'
    $htmlcode += '<strong>... Next Steps: </strong><br /><br />'
    $htmlcode += '<a href= "/bb/doc/EN.pdf">- Activate your Device</a>&nbsp;<br />'
    $htmlcode += '&nbsp;&nbsp;To be able to use your new BlackBerry you need to complete this steps.<br /><br />'
    $htmlcode += '<a href= "/bb/doc/Tips.pdf">- Tips and Tricks for your Device</a><br />'
    $htmlcode += '&nbsp;&nbsp;Tips and Tricks to make your Device experience a success.<br /><br />'
    $htmlcode += '<strong>... in case you require technical support:</strong><br /><br />'
    $htmlcode += 'If you experiance problems with your Device, please contact your local IT-Support.<br /><br />'
    $htmlcode += 'Thank You.'
    $htmlcode += '<br/><div></body></html>'
    Send-MailMessage -to $UsrData.Email -From $from -Body $htmlcode -SmtpServer $smtp -Subject $subject -BodyAsHtml
    If you want to make sure the mail is displayed as a HTML Mail add to the send-mailmessage the option
    -BodyAsHtml
    Regards
    Dan

  • How to send a mail with HTML body from Oracle

    Hi Team,
    Can somebody guide me how to send a mail with HTML body from oracle.
    Here is the piece of code i am trying to send a mail.
    procedure SEND_MAIL is
    cursor c_1 is select * from table_name;
    l_mail_id varchar2(40);
    -- ls_mailhost VARCHAR2(64) := Mailhost;
    ls_from VARCHAR2(64) := ‘[email protected]
    ls_subject VARCHAR2(200);
    ls_to VARCHAR2(64);
    l_mail_conn UTL_SMTP.connection;
    ls_left_menu_name VARCHAR2(64);
    ll_emp_num number(8);
    begin
    for i in c_1 loop
    begin
    l_mail_conn := UTL_SMTP.OPEN_CONNECTION('IP');
    UTL_SMTP.HELO(l_mail_conn, 'IP');
    UTL_SMTP.MAIL(l_mail_conn, LS_FROM);
    UTL_SMTP.RCPT(L_mail_conn, LS_TO);
    UTL_SMTP.DATA(l_mail_conn,'From: ' ||ls_from || utl_tcp.crlf ||
    'To: ' ||ls_to || utl_tcp.crlf ||
    'Subject: ' ||ls_subject|| utl_tcp.crlf);
    UTL_SMTP.QUIT(l_mail_conn);
    exception
    when no_data_found then
    null;
    when others then
    RAISE_APPLICATION_ERROR(-20000, 'Failed to send mail due to the following error: ' || sqlerrm);
    end;
    end loop;
    end;
    Thnx

    Hi Nicolas!
    Have you tried to set "Output Format" for "RAW Text" to HTM in SCOT.
    If HTM is missing in your dropdown-list, you could check out table SXCONVERT2. Copy the line with category T/format TXT, and change the format from TXT to HTM. The existing function
    SX_OBJECT_CONVERT__T.TXT does not need to be changed. Now you should be able to choose HTM in SCOT. You will probably need som HTML-tags in your text to make it look good.
    Hope this helps!
    Regards
    Geir

  • Sending � signs with JavaMail

    Hi chaps,
    At our company we use the JavaMail API through JNI to send emails externally to customers.
    Recently the business has decided that it would be nice to send pound (�) through, however it's not going to plan.
    Normally the messages are encoded in 7-bit which would seem to exclude the � (163), however it seems that it is first converted to a (=80, hex with no ascii correlation) and then to a Euro symbol.
    I've tried setting the "allow8bitmime" property in order to enable the SMTP service to support 8-bit encoding, but it's not working AND Microsoft say that our Exchange (v5.5) doesn't support 8-bit MIME types. The odd thing is that sending external emails via Exchange supports the � with no problems and is read in the mail reader as 8-bit encoded (!).
    Has anybody had any experience with issues like this ? Any reply appreciated.
    Thanks
    Ammonite

    Ammonite,
    I am working on a similar problem.. Did you say your
    email gets translated and prints the Euro symbol... I
    actually need out email to print Both the pound and
    the Euro and it does niether right now.. The current implementation I am working on will display a Euro instead of a pound, although this isn't by design. The message is encoded using "Quoted-Printable" and substitutes the pound for a =80 character. How this maps to a Euro is unknown to me :(
    In standard ascii the pound is outside the standard 7-bit encoding range (163) and featured in the Extended Set on the platform we use. I'm not sure about the Euro. The Iso-8859-1 charset which SH provided supports the pound in "Quoted-Printable" encoding, but this hasn't been well received by JavaMail MIME objects that I have tried.
    I haven't managed any sort of 8-bit encoding with JavaMail as yet, due to supposed lack of support in Exchange 5.5 and lack of response to the "allow8bitmime" property.
    does anyone know is using MimeMessage limit the
    message to ASCII characters only and does that rule
    out the Euro and the Pound symbol/
    It shoudn't rule them out, but I'm starting to believe that MimeMessages are necessarily helping things here :)

Maybe you are looking for