利用JAVAMail发取和发送gmail邮件

本文提供了一段使用JavaMail API通过安全套接字层SSL连接来收发Gmail邮件的示例代码。包括配置SSL连接、设置认证信息及实现邮件的接收与发送过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Gmail目前已经启用了POP3和SMTP服务,与其他邮箱不同的是Gmail提供的POP3和SMTP是使用安全套接字层SSL的,因此常规的JavaMail程序是无法收发邮件的,下面是使用JavaMail如何收取Gmail邮件以及发送邮件的代码:

1. 邮件收取

package cn.test;

import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;


/**
 * 用于收取Gmail邮件
 * 
 */

public class GmailFetch {

    public static void main(String argv[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
        props.setProperty("mail.pop3.port", "995");
        props.setProperty("mail.pop3.socketFactory.port", "995");

        // 以下步骤跟一般的JavaMail操作相同
        Session session = Session.getDefaultInstance(props, null);

        URLName urln = new URLName("pop3", "pop.gmail.com", 995, null,"[邮箱帐号]", "[邮箱密码]");

        Store store = session.getStore(urln);

        Folder inbox = null;

        try {

            store.connect();

            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);

            Message[] messages = inbox.getMessages();
            inbox.fetch(messages, profile);
            System.out.println("收件箱的邮件数:" + messages.length);

            for (int i = 0; i < messages.length; i++) {
                // 邮件发送者
                String from = decodeText(messages[i].getFrom()[0].toString());
                InternetAddress ia = new InternetAddress(from);
                System.out.println("FROM:" + ia.getPersonal() + ia.getAddress());

                // 邮件标题
                System.out.println("TITLE:" + messages[i].getSubject());

                // 邮件大小
                System.out.println("SIZE:" + messages[i].getSize());

                // 邮件发送时间
                System.out.println("DATE:" + messages[i].getSentDate());
            }
        } finally {
            try {
                inbox.close(false);
            } catch (Exception e) {
            }

            try {
                store.close();

            } catch (Exception e) {

            }
        }
    }

     protected static String decodeText(String text) throws UnsupportedEncodingException {

        if (text == null)
            return null;

        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;

    }

}


2. 发送邮件

package cn.test;
 
import java.security.Security;
import java.util.Date;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 使用Gmail发送邮件
 * 
 */

public class GmailSender {

    public static void main(String[] args) throws AddressException,MessagingException {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object

        Properties props = System.getProperties();

        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");

        final String username = "[邮箱帐号]";
        final String password = "[邮箱密码]";

        Session session = Session.getDefaultInstance(props, new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

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

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@mo168.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[收件人地址]", false));
        msg.setSubject("Hello");
        msg.setText("How are you");
        msg.setSentDate(new Date());
        Transport.send(msg);

        System.out.println("Message sent.");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值