郵件開發:傳送程式

恆奇恆毅發表於2016-01-07

l使用JavaMail傳送一封簡單的郵件
Ø建立包含郵件伺服器的網路連線資訊的Session物件。
Ø建立代表郵件內容的Message物件。
Ø建立Transport物件、連線伺服器、傳送Message、關閉連線。
l應用Authenticator類實現使用者資訊驗證
Ø結合Transport.send靜態方法使用。



public class MailSender_simple {
    public static void main(String[] args) throws Exception{
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");//設定需要認證,來源於郵件協議,在文件中也有
        props.setProperty("mail.transport.protocol", "smtp");//設定協議

        
        /**
         * 注意與getDefaultInstance的區別,getInstance返回新的,getDefaultInstance返回原來使用過的
         */
        Session session = Session.getInstance(props);//3準備環境
        session.setDebug(true);//把所有的除錯資訊打出來
        
        Message msg = new MimeMessage(session);//1製造郵件、衛星
        msg.setSubject("test from javamail");
        msg.setText("test from javamail");//簡單的文字
        /**
         * 需要與你登陸的一致,否則不成功
         */
        msg.setFrom(new InternetAddress("xxssyyyyssxx@126.com"));//給郵件閱讀器使用的
    
        Transport transport = session.getTransport();//2製造發射器、火箭
//        transport.connect("smtp.sohu.com",25,"xxssyyyyssxx","xsy881026");
        transport.connect("smtp.126.com",25,"xxssyyyyssxx","xsy881026");
        //一般情況下只需要使用靜態方法send,但是如果需要傳送給多個人,就需要使用這種方法,先connnect    ,再傳送
        //收件人也是如此
        transport.sendMessage(msg,new Address[]{new InternetAddress("xxssyyyyssxx@sohu.com")});
        transport.close();
    }

}







/**
 * 具有smtp功能的傳送器
 * @author 熊詩言
 *
 */
public class SMTPMailSender {
    public static void main(String[] args) throws Exception{
//        System.setProperty("socksProxyHost", "proxy2.lh.petrochina");
//        System.setProperty("socksProxyPort", "8080");

        Properties props = new Properties();
        props.setProperty("mail.smtp.localhost", "mail.xsy.com");//其他伺服器用於去頂主機身份
        props.setProperty("mail.transport.protocol", "smtp");//設定協議
        
        /**
         * 注意與getDefaultInstance的區別,getInstance返回新的,getDefaultInstance返回原來使用過的
         */
        Session session = Session.getInstance(props);//3準備環境
        session.setDebug(true);//把所有的除錯資訊打出來
        
        Message msg = new MimeMessage(session);//1製造郵件、衛星
        msg.setSubject("test from javamail");
        msg.setText("test from javamail");//簡單的文字
        String to = "xxssyyyyssxx@sohu.com";
        msg.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        msg.setFrom(new InternetAddress("xxssyyyyssxx@126.com"));//給郵件閱讀器使用的
        
        msg.saveChanges();
    
        Transport transport = session.getTransport("smtp");//2製造發射器、火箭
        String domain = to.substring(to.indexOf("@")+1);
        String server = getSMTPServer(domain,null);
        transport.connect(server,25,null,null);
        transport.sendMessage(msg,msg.getAllRecipients());
        transport.close();
    }

    private static String getSMTPServer(String domain, String dnsServer) throws NamingException {
        DirContext dirContext = new InitialDirContext();
        Attributes mxAttribute = null;
        if(dnsServer!=null){
            mxAttribute = dirContext.getAttributes("dns:"+dnsServer+"/"+domain,
                new String[]{"MX"});
        }else {
            mxAttribute = dirContext.getAttributes("dns:"+"/"+domain,
                    new String[]{"MX"});
        }
        String record = (String) mxAttribute.get("MX").get();
        String smtp = record.substring(record.indexOf(" ") + 1);
        return smtp;
    }

}






public class MailSender_auth_send {
    public static void main(String[] args) throws Exception{
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.126.com");
        Session session = Session.getInstance(props,
                new Authenticator()
                {
                    @Override/*策略模式,程式碼封裝*/
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication("xxssyyyyssxx","xsy881026");
                    }
                }
        );

        session.setDebug(true);
        
        //*
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("xxssyyyyssxx@126.com"));
        msg.setSubject("test中文");
        //抄送:在發給你的時候也給另外一個人傳送一份,你知道
        //暗送:在發給你的時候也給另外一個人傳送一份,你不知道
        msg.setRecipients(RecipientType.TO,
                InternetAddress.parse("熊詩言<xxssyyyyssxx@sohu.com>,yanshixiong@126.com"));
        msg.setContent("<span style='color:red'>中文</span>", "text/html;charset=gbk");
        
        
        Transport.send(msg);//*/
        
        /*
        //直接傳送一封寫好的郵件,這個由郵件客戶端生成
        Message msg = new MimeMessage(session,new FileInputStream("D:\\WorkSpace\\javamail\\classesresouce\\demo3.eml"));
        Transport.send(msg,InternetAddress.parse("xxssyyyyssxx@sohu.com"));//*/
    }

}



相關文章