JavaMail文件發(fā)送

郵箱開啟SMTP


image.png

導包

     <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
public class SendMail {
    public static void main(String [] args)
    {
        // 收件人電子郵箱
        String to = "xx@qq.com";

        // 發(fā)件人電子郵箱
        String from = "xx@qq.com";

        // 指定發(fā)送郵件的主機為 localhost
        String host = "smtp.qq.com";  //QQ 郵件服務(wù)器

        // 獲取系統(tǒng)屬性
        Properties properties = System.getProperties();

        // 設(shè)置郵件服務(wù)器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 獲取默認session對象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("xxx@qq.com", ""); //發(fā)件人郵件用戶名,密碼是郵箱的授權(quán)碼,不是登錄密碼
            }
        });

        try{
            // 創(chuàng)建默認的 MimeMessage 對象。
            MimeMessage message = new MimeMessage(session);

            // Set From: 頭部頭字段
            message.setFrom(new InternetAddress(from));

            // Set To: 頭部頭字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // Set Subject: 頭字段
            message.setSubject("This is the Subject Line!");

            // 創(chuàng)建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText("This is message body");

            // 創(chuàng)建多重消息
            Multipart multipart = new MimeMultipart();

            // 設(shè)置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分
            messageBodyPart = new MimeBodyPart();
            String filename = "wanted.png";
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);

            // 發(fā)送完整消息
            message.setContent(multipart );

            //   發(fā)送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        }catch (Exception   mex) {
            mex.printStackTrace();
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容