Java收发邮件

第一步对邮箱进行配置,以QQ邮箱为例,先在邮箱设置里面选择账户

Java收发邮件_第1张图片

然后开启服务,这一步需要短信验证,通过之后会生成授权码,记下来,一会有用

Java收发邮件_第2张图片

第二步打开eclipse,建立项目,导入jar包,我用的jar包是mail-1.4.7.jar

收邮件代码如下:

import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;

/**
 * 发送邮件
 * setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者类型,但是一般用后两个,这样可以避免意外的替换或者覆盖接受者名单。定义接受者类型:
 *Message.RecipientType.TO:消息接受者
 *Message.RecipientType.CC:消息抄送者
 *Message.RecipientType.BCC:匿名抄送接收者(其他接受者看不到这个接受者的姓名和地址)
 * @author rhy
 * @date 2018-7-23 下午3:11:05
 * @version V1.0
 */

public class sendEmail {
	public static void main(String[] args) {
        String host = "imap.qq.com";
        int port = 993;
        String username = "填写你的邮箱";
        String password = "填写你的密码或者开启服务时的授权码";
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = System.getProperties();  
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);  
        props.setProperty("mail.imap.socketFactory.port","993");  
        props.setProperty("mail.store.protocol","imap");    
        props.setProperty("mail.imap.host", host);    
        props.setProperty("mail.imap.port", "993");    
        props.setProperty("mail.imap.auth.login.disable", "true"); 
        Session session = Session.getDefaultInstance(props,null);  
        session.setDebug(false);  
        IMAPFolder folder= null;
        IMAPStore store=null;
        try {   
            store=(IMAPStore)session.getStore("imap");  // 使用imap会话机制,连接服务器
            store.connect(host,port,username,password);
            folder=(IMAPFolder)store.getFolder("Sent Messages"); //收件箱 

            Folder defaultFolder = store.getDefaultFolder(); 
            Folder[] allFolder = defaultFolder.list();
          for (int i = 0; i < allFolder.length; i++) {
                System.out.println("这个是服务器中的文件夹="+allFolder[i].getFullName());
            }
              // 使用只读方式打开收件箱 
            folder.open(Folder.READ_WRITE);
            int size = folder.getMessageCount();
            System.out.println("这里是打印的条数=="+size);
            Message[] mess=folder.getMessages();
          //  Message message = folder.getMessage(size);
            for (int i = 0; i <5; i++) {
                String from = mess[i].getFrom()[0].toString();
                String subject = mess[i].getSubject();
                Date date = mess[i].getSentDate();
                System.out.println("From: " + from);
                System.out.println("Subject: " + subject);
                System.out.println("Date: " + date);
            }
           /* String from = message.getFrom()[0].toString();
            String subject = message.getSubject();
            Date date = message.getSentDate();*/
           /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); */ 

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                if (folder != null) {
                    folder.close(false);
                }
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
        System.out.println("接收完毕!");
    }
}

 

 

 

发邮件(只是一个简单的发文本邮件的例子):

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class sendEmails {

	public static void main(String[] args) throws MessagingException, GeneralSecurityException {
        //创建一个配置文件并保存
        Properties properties = new Properties();

        properties.setProperty("mail.host","smtp.qq.com");

        properties.setProperty("mail.transport.protocol","smtp");

        properties.setProperty("mail.smtp.auth","true");


        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("你的邮箱","你的授权码");
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect("smtp.qq.com","你的邮箱","你的授权码");

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("你的邮箱"));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("接收邮箱"));

        //邮件标题
        mimeMessage.setSubject("Hello Mail");

        //邮件内容
        mimeMessage.setContent("我的想法是把代码放进一个循环里","text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();
    }
	
}


可能出现的问题:报Access to default session denied

解决方法:

getDefaultInstance替换为getInstance

原代码:

Session session = Session.getDefaultInstance(properties, new Authenticator()

改为:

Session session = Session.getInstance(properties, new Authenticator()

原因:Session.getDefaultInstance()是获得一个默认的共享session
 

 

你可能感兴趣的:(Java收发邮件)