关闭

java_mail收发邮件,绝对简单,绝对可用

781人阅读 评论(0) 收藏 举报

关于javamail,网上沸沸扬扬的说了一大堆,代码也是东一块西一块的。其实理论知识再说也不如真正给个简单的代码看看,这个代码绝对简单,绝对可以运行。

代码如下:至于lib包需要的可以从以下地址获得。

http://www2.cnalbum.cn/java/?C=D;O=D

ConstantsMail.java

package com.test.mail;

public class ConstantsMail {

    //"mail.smtp.host"  通常无需更改
    public static final String MAIL_SMTP_HOST = "mail.smtp.host";
    //"mail.smtp.auth"  通常无需更改
    public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
    //需要身份验证  通常无需更改
    public static final String TRUE = "true";
    //连接协议 "pop3"  通常无需更改
    public static final String POP3 = "pop3";
    //收件箱  通常无需更改
    public static final String INBOX = "INBOX";
   
   
    //连接的smtp服务器的名称
    public static final String CONN_SMTP_SERVER_NAME = "smtp.softbrain.com.cn";
    //连接服务器用户名 
    public static final String CONN_SERVER_USER_NAME = "jiangbin@softbrain.com.cn";
    //连接服务器密码 
    public static final String CONN_SERVER_PASSWORD = "softbrain";
   
   
    //邮件标题
    public static final String MAIL_TITLE = "title";
    //邮件内容
    public static final String MAIL_CONTENT = "content";
   
   
    //邮件接收格式
    public static final String MAIL_REC_PATTERN_1 = "text/html; charset=GB2312";
    public static final String MAIL_REC_PATTERN_2 = "texl/plain";
    public static final String MAIL_REC_PATTERN_3 = "multipart/alternative";
    public static final String MAIL_REC_PATTERN_4 = "multipart/related";
   
   
    //发件人地址和姓名 
    public static final String MAIL_SENDER_ADDRESS = "jiangbin@softbrain.com";
    public static final String MAIL_SENDER_NAME = "aaaaa";
    //收件人地址和姓名
    public static final String MAIL_RECEIVER_ADDRESS = "jiangbin19830421@163.com";
    public static final String MAIL_RECEIVER_NAME = "bbbbbb";
    //抄送人地址和姓名
    public static final String MAIL_COPYER_ADDRESS = "lanisha00006@163.com";
    public static final String MAIL_COPYER_NAME = "lanisha00006";
}

MailUtil.java

package com.test.mail;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.MessagingException;

public class MailUtil {

    //获得所有邮件
    public static int getMessageCount(Folder folder) throws MessagingException{
        int count = 0 ;
        if(folder != null)
            return folder.getMessageCount();
        return count ;
    }

    //获得新邮件的个数
    public static int getNewMessageCount(Folder folder) throws MessagingException{
        int count = 0 ;
        if(folder != null)
            return folder.getNewMessageCount();
        return count ;
    }
   
    //已经读取的邮件的个数
    public static int getUnreadMessageCount(Folder folder) throws MessagingException{
        int count = 0 ;
        if(folder != null)
            return folder.getUnreadMessageCount();
        return count ;
    }
   
    //初始化属性文件
    public static Properties initProps(){
        Properties props = new Properties();
        //设置smtp的服务器地址
        props.put(ConstantsMail.MAIL_SMTP_HOST,ConstantsMail.CONN_SMTP_SERVER_NAME);
        //设置smtp服务器要身份验证
        props.put(ConstantsMail.MAIL_SMTP_AUTH,ConstantsMail.TRUE);
        return props ;
    }
   
}

PopupAuthenticator.java

package com.test.mail;

import javax.mail.*;

public class PopupAuthenticator extends Authenticator{
    String username=null;
    String password=null;
    public PopupAuthenticator(){
    }
    public PasswordAuthentication performCheck(String user,String pass){
         this.username = user;
         this.password = pass;
        return getPasswordAuthentication();
    }
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}

RecMail.java

package com.test.mail;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;

public class RecMail {

    public static void main(String[] args) {
        Properties props = MailUtil.initProps();
        try {
            PopupAuthenticator popAuthenticator = new PopupAuthenticator() ;
            //身份验证
            PasswordAuthentication auth = popAuthenticator.performCheck(ConstantsMail.CONN_SERVER_USER_NAME,ConstantsMail.CONN_SERVER_PASSWORD);
            //获得session实例
            Session session = Session.getInstance(props, popAuthenticator);
            //获得连接协议
            Store store = session.getStore(ConstantsMail.POP3);
            store.connect(ConstantsMail.CONN_SMTP_SERVER_NAME, ConstantsMail.CONN_SERVER_USER_NAME, ConstantsMail.CONN_SERVER_PASSWORD);
            Folder folder = store.getFolder(ConstantsMail.INBOX);
            folder.open(Folder.READ_WRITE);

            //邮件的总数
            System.out.println("总共有"+MailUtil.getMessageCount(folder)+"封邮件。");
            //新邮件的个数
            System.out.println("新邮件的个数是"+MailUtil.getNewMessageCount(folder)+"封");
            //邮件中没有读过的
            System.out.println("已经读取了"+MailUtil.getUnreadMessageCount(folder)+"封");
           
            Message messages[] = folder.getMessages();
            if(messages.length==0){
                System.out.println("未收到新邮件...");
            }
            for(int i=0;i<messages.length;i++){
                System.out.println("第"+(i+1)+"条:"+":"+((MimeMessage)messages[i]).getSubject());
            }
            folder.close(true);
            store.close();
         }catch (Exception e) {
            System.out.println("errors on "+e.getMessage());
         }
    }
}

SendMail.java

package com.test.mail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMail {
    public static void main(String[] args) {
        System.out.println("sending message ......");
        Properties props = MailUtil.initProps();
        try {
            PopupAuthenticator popAuthenticator = new PopupAuthenticator() ;
            //身份验证
            PasswordAuthentication auth = popAuthenticator.performCheck(ConstantsMail.CONN_SERVER_USER_NAME,ConstantsMail.CONN_SERVER_PASSWORD);
            //获得session实例
            Session session = Session.getInstance(props, popAuthenticator);
           
            //发送人地址 后面显示是接收的邮箱中发件人的名字
            Address addressFrom = new InternetAddress(ConstantsMail.MAIL_SENDER_ADDRESS,ConstantsMail.MAIL_SENDER_NAME);
            //收件人地址 后面的参数是收件人打开邮件以后显示收件人的名称
            Address addressTo = new InternetAddress(ConstantsMail.MAIL_RECEIVER_ADDRESS,ConstantsMail.MAIL_RECEIVER_NAME);
            //抄送地址 后面的参数说明同收件人
            Address addressCopy = new InternetAddress(ConstantsMail.MAIL_COPYER_ADDRESS,ConstantsMail.MAIL_COPYER_NAME);
            //创建邮件体
            Message message = new MimeMessage(session);
            //设置邮件的内容
            //message.setContent(content, model);
            //message.setText("aaaaaaaaaaaaaaaaaaa");
            //设置邮件的标题
            message.setSubject(ConstantsMail.MAIL_TITLE);
            //发件人地址
            message.setFrom(addressFrom);
           
            //收件人地址,可以多次添加
            message.addRecipient(Message.RecipientType.TO,addressTo);
            //抄送人地址,可以多次添加
            message.addRecipient(Message.RecipientType.CC,addressCopy);
           
            //上传附件
            Multipart multipart = new MimeMultipart();
            MimeBodyPart bodypart = new MimeBodyPart();
            /*1 取得本地硬盘的文件上传
             *  本地的文件当不使用setFileName的时候可以把文件的内容显示在下面
             *  但是会出现乱码。。。。。。????
             */
            DataSource datasource =  new FileDataSource("E://my//集合.txt");
            bodypart.setDataHandler(new DataHandler(datasource));
            //文件下载时的标题,若不设置名称,则会把内容显示在下面,但是会出现乱码
            bodypart.setFileName(MimeUtility.encodeWord("测试附件.doc","gb2312", null));
            multipart.addBodyPart(bodypart);
           
            /*2 直接创建附件上传。并且附件内容为"11111111"
             *  自己创建的文件不能当作内容显示在下面,只能当作附件
             *  若不设置文件名setFileName,则会临时产生一个名字
             */
            MimeBodyPart bodypart1 = new MimeBodyPart();
            //以下2种方式都可以
            //bodypart1.setText("哈哈");
            bodypart1.setContent("哈哈哈",ConstantsMail.MAIL_REC_PATTERN_1);
            //文件下载时的标题
            bodypart1.setFileName(MimeUtility.encodeWord("测试1.txt","gb2312", null));
            multipart.addBodyPart(bodypart1);
           
            //设置上传文件,可以上传多个文件
            message.setContent(multipart);
            //附件测试end...
           
           
            message.saveChanges();

            Transport transport = session.getTransport("smtp");
            //连接发件人的服务器
            transport.connect(ConstantsMail.CONN_SMTP_SERVER_NAME, ConstantsMail.CONN_SERVER_USER_NAME, ConstantsMail.CONN_SERVER_PASSWORD);
            //发送至服务器
            Transport.send(message);
            //关闭连接
            transport.close();
            System.out.println("message send ......");
        } catch (Exception e) {
            System.out.println("errors on "+e.getMessage());
        }
    }
}

基本上是不用修改的,而且我觉得里面的说明应该是比较清楚的。

只需要修改ConstantsMail.java里面相应的参数就可以了。

绝对好用的代码。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:254268次
    • 积分:3850
    • 等级:
    • 排名:第8263名
    • 原创:112篇
    • 转载:64篇
    • 译文:0篇
    • 评论:52条
    文章分类
    最新评论