无酒也疯狂

博客园 首页 新随笔 联系 订阅 管理

用javamail发送邮件的实例网上一大堆,但发现太详细了,这里给出最核心,最简单,但可以工作的代码。

 

package test.net;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class SendMailTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        String from = "soemone@any.com";
        
        Properties pps = new Properties();
        final String userName = "anyone@any.com";
        final String password = "password";
                
        String host = "smtp.163.com";
        pps.setProperty("mail.smtp.host", host);
        pps.setProperty("mail.user", userName);
        pps.setProperty("mail.password", password);
        pps.setProperty("mail.smtp.auth", "true");
        pps.put("mail.smtp.starttls.enable", "true");
        
        
        Session s = Session.getDefaultInstance(pps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                
                return new PasswordAuthentication(userName, password);
                
            }
        });
        
        try {
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(RecipientType.TO, new InternetAddress("martin.zhang717@gmail.com"));
            msg.setSubject("subject line");
            msg.setText("this is text line");
            
            Transport.send(msg);
            System.out.println("Msg Sent");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        System.out.println("DONE");
        
    }

}

 

 

posted on 2012-09-12 14:56  葬。  阅读(241)  评论(0)    收藏  举报