Java實現發郵件功能


代碼如下:

package com.weimob.finance.utils;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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;

/**
 * Java Mail 工具類
 *  
 * @author XueQi
 * @version 1.0
 *  
 */  
public class MailUtils {  
    private static String host;  
    private static String username;  
    private static String password;  
    private static String from;  
    private static String nick;  
 
    static {  
        try {  
            // Test Data  
            host = "smtp.qq.com";  
            username = "yourqq@qq.com";  
            password = "*******";  
            from = "yourqq@qq.com";  
            nick = "nickinfo";  
            // nick + from 組成郵箱的發件人信息  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
 
    /**
     * 發送郵件
     *  
     * @param to
     *            收件人列表,以","分割
     * @param subject
     *            標題
     * @param body
     *            內容
     * @param filepath
     *            附件列表,無附件傳遞null
     * @return
     * @throws MessagingException
     * @throws AddressException
     * @throws UnsupportedEncodingException
     */  
    public static boolean sendMail(String to, String subject, String body,  
            List<String> filepath) throws AddressException, MessagingException,  
            UnsupportedEncodingException {  
        // 參數修飾  
        if (body == null) {  
            body = "";  
        }  
        if (subject == null) {  
            subject = "無主題";  
        }  
        // 創建Properties對象  
        Properties props = System.getProperties();  
        // 創建信件服務器  
        props.put("mail.smtp.host", host);  
        props.put("mail.smtp.auth", "true"); // 通過驗證  
        props.put("mail.smtp.port", "465");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.ssl.enable", "true");
       //props.put("mail.debug", "true");
        // 得到默認的對話對象  
        Session session = Session.getDefaultInstance(props, null);  
        // 創建一個消息,並初始化該消息的各項元素  
        MimeMessage msg = new MimeMessage(session);  
        nick = MimeUtility.encodeText(nick);  
        msg.setFrom(new InternetAddress(nick + "<" + from + ">"));  
        // 創建收件人列表  
        if (to != null && to.trim().length() > 0) {  
            String[] arr = to.split(",");  
            int receiverCount = arr.length;  
            if (receiverCount > 0) {  
                InternetAddress[] address = new InternetAddress[receiverCount];  
                for (int i = 0; i < receiverCount; i++) {  
                    address[i] = new InternetAddress(arr[i]);  
                }  
                msg.addRecipients(Message.RecipientType.TO, address);  
                msg.setSubject(subject);  
                // 后面的BodyPart將加入到此處創建的Multipart中  
                Multipart mp = new MimeMultipart();  
                // 附件操作  
                if (filepath != null && filepath.size() > 0) {  
                    for (String filename : filepath) {  
                        MimeBodyPart mbp = new MimeBodyPart();  
                        // 得到數據源  
                        FileDataSource fds = new FileDataSource(filename);  
                        // 得到附件本身並至入BodyPart  
                        mbp.setDataHandler(new DataHandler(fds));  
                        // 得到文件名同樣至入BodyPart  
                        mbp.setFileName(fds.getName());  
                        mp.addBodyPart(mbp);  
                    }  
                    MimeBodyPart mbp = new MimeBodyPart();  
                    mbp.setText(body);  
                    mp.addBodyPart(mbp);  
                    // 移走集合中的所有元素  
                    filepath.clear();  
                    // Multipart加入到信件  
                    msg.setContent(mp);  
                } else {  
                    // 設置郵件正文  
                    msg.setText(body);  
                }  
                // 設置信件頭的發送日期  
                msg.setSentDate(new Date());  
                msg.saveChanges();  
                // 發送信件  
                Transport transport = session.getTransport("smtp");  
                transport.connect(username, password);
                transport.sendMessage(msg,  
                        msg.getRecipients(Message.RecipientType.TO));  
                transport.close();  
                return true;  
            } else {  
                System.out.println("None receiver!");  
                return false;  
            }  
        } else {  
            System.out.println("None receiver!");  
            return false;  
        }  
    }  
 
    public static void main(String[] args) throws AddressException,  
            UnsupportedEncodingException, MessagingException {  
        sendMail("toother@qq.com,yourqq@qq.com", "注冊信息郵件", "注冊郵件,有附件", null);
        System.out.println("sendMail success!");
    }  
}

准備過程:

1.QQ郵箱兩個

2.發送郵件的jar包

mail.jar

<dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>

</dependency>

3.用QQ給QQ發送郵件,發送方得開啟第三方登錄,也就是授權登錄,下面就是獲取授權碼解釋鏈接

需要開始POP3和SMTP,還有點擊生成授權碼

4.java代碼(上面已附)

5運行,最后顯示 250 Mail OK即發送成功

中間可能遇到的問題:

1.郵箱,帳號,密碼配置不正確導致報connection failed error!

2.郵箱沒有開啟smpt協議。如上面步驟3操作

3.報 java.io.FileNotFoundException: 

原因是,eclipse 自帶的mail jar包與maven導入的mail jar包沖突,刪除掉j2ee中mail jar ,沖突即可解決!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM