09-09
22

完整的javamail收发信程序

沒想到都過了一年了還有人寄信給我要程式.......
我就把之前測試的程式波出來討論吧

發信的部分如下:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailUsingAuthentication
{
    private static final String SMTP_HOST_NAME = "gmail-smtp.l.google.com";
    private static final String SMTP_AUTH_USER = "GMAIL.ACCOUNT@gmail.com";
    private static final String SMTP_AUTH_PWD = "YOUR PASSWORD";
    private static final String emailMsgTxt = "Please visit my project at ";
    private static final String emailSubjectTxt = "Order Confirmation Subject";
    private static final String emailFromAddress = "GMAIL.ACCOUNT@gmail.com";
    private static final String[] emailList = { "FRIENDS.GMAIL.ACCOUNT.1@gmail.com" ,"FRIENDS.GMAIL.ACCOUNT.2@gmail.com"};

    public static void main(String args[]) throws Exception
    {
//         System.setProperty( "proxySet", "true" );
//         System.setProperty( "http.proxyHost", "wwwcache.ncl.ac.uk" );
//         System.setProperty( "http.proxyPort", "8080" );
        
        SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
        smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }

    public void postMail(String recipients[], String subject, String message, String from) throws MessagingException
    {
        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
    
    private class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }
}





收信的部分如下:
// Fetching Mail

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetMessageExample
{
  public static void main(String args[]) throws Exception
  {
    if (args.length != 2)
    {
      System.err.println("Usage: java MailExample host username password");
      System.exit(-1);
    }

    String username = args[0];
    String password = args[1];
    
    // Create empty properties
    Properties props = new Properties();
    
//     props.setProperty("proxySet", "true");
//     props.setProperty("proxyHost", "wwwcache.ncl.ac.uk");
//     props.setProperty("proxyPort", "8080");

    props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.pop3.socketFactory.fallback", "false");
    props.setProperty("mail.pop3.port", "995");
    props.setProperty("mail.pop3.socketFactory.port", "995");
    
    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect("pop.gmail.com", username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++)
    {
      System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());

      System.out.println("Read message? [Y to read / N to end]");
      String line = reader.readLine();
      if ("Y".equalsIgnoreCase(line))
      {
        System.out.println(message[i].getContent());
      }
      else if ("N".equalsIgnoreCase(line))
      {
        break;
      }
    }

    // Close connection
    folder.close(false);
    store.close();
  }
}





發信程式的測試方法,只要把static field的
1. SMTP_AUTH_USER 改成你的信箱
2. SMTP_AUTH_PWD 改成你的密碼
3. emailList 加入收信人的信箱列表
4. emailMsgTxt, emailSubjectTxt 和 emailFromAddress要不要換都沒有差吧!?
上述改完後就可以跑跑看了..

收信更簡單args的參數
args[0] = 你的信箱
args[1] = 你的密碼
程式會將你的subject列出來...

注意在測試前要先將信箱設定為接受pop3

参考地址:http://www.javaworld.com.tw/jute/post/view?bid=5&id=126890&tpg=1&ppg=1&sty=1&age=0

文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: javamail
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.