2013年8月8日 星期四

Java send mail using gmail and support utf-8 characters



Step 1. Download the jar
Download the jar of javax.mail.jar from oracle send mail , and I used the JavaMail 1.5.0 version of 


Step 2. Example Using connecttion to gmail
 please notice the red color character.
// ---------------
public void test_gmail2 () throws Exception {
      
            final String SMTP_HOST_NAME = "smtp.gmail.com";
            final String SMTP_HOST_PORT = "465";
            final String SMTP_AUTH_USER = "your_Gmail@gmail.com";
            final String SMTP_AUTH_PWD = "your_Gmail_Password";

            Properties props = new Properties();

            props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtps.host", "smtp.gmail.com");
            props.put("mail.smtps.auth", "true");
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.smtp.socketFactory.port", SMTP_HOST_PORT);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
                  
            Session mailSession = Session.getInstance(props,  new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
                }
              });
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport("smtps");

            MimeMessage message = new MimeMessage(mailSession);
             message.setSubject("這是Testing SMTP-SSL");
            message.setContent("<h3>This</h3> is a test 信", "text/html;charset=utf-8");
          
         
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("Sender_mail"));

          
            /**/
            transport.connect
              (SMTP_HOST_NAME, Integer.parseInt(SMTP_HOST_PORT), SMTP_AUTH_USER, SMTP_AUTH_PWD);

            transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
            transport.close();
 }
    

1 則留言:

  1. Exception:
    javax.mail.MessagingException: can't determine local email address

    solution:
    setting your /etc/hosts file such as
    127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4

    回覆刪除