javamail

Wesley13
• 阅读 424
package com.syj;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
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;


/**
 * <p>
 * Title:用java发送邮件的例子
 * </p>
 * 
 * <p>
 * Description:发送图片附件并在html中使用该图片
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2007
 * </p>
 * 
 * @author 孙钰佳 
 * @blog http://blog.csdn.net/sunyujia/
 * @main sunyujia@yahoo.cn
 * @date Jun 10, 2008 12:35:26 AM
 */
public class SendMail {
    private static String username = "xxxx";
    private static String password = "xxxx";
    private static String smtpServer = "smtp.163.com";
    private static String fromMailAddress = "xxxx@163.com";
    private static String toMailAddress = "sunyujia@yahoo.cn";

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpServer);
        // 获得邮件会话对象
        Session session = Session.getDefaultInstance(props,
                new SmtpAuthenticator(username, password));
        /** *************************************************** */
        // 创建MIME邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromMailAddress));// 发件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(
                toMailAddress));// 收件人
        mimeMessage.setSubject("主题");
        mimeMessage.setSentDate(new Date());// 发送日期
        Multipart mp = new MimeMultipart("related");// related意味着可以发送html格式的邮件
        /** *************************************************** */
        BodyPart bodyPart = new MimeBodyPart();// 正文
        bodyPart.setDataHandler(new DataHandler("测<img src=/"cid:IMG1/" />试",
                "text/html;charset=GBK"));// 网页格式
        /** *************************************************** */
        BodyPart attachBodyPart = new MimeBodyPart();// 普通附件
        FileDataSource fds = new FileDataSource("c:/boot.ini");
        attachBodyPart.setDataHandler(new DataHandler(fds));
        attachBodyPart.setFileName("=?GBK?B?"
                + new sun.misc.BASE64Encoder().encode(fds.getName().getBytes())
                + "?=");// 解决附件名中文乱码
        mp.addBodyPart(attachBodyPart);
        /** *************************************************** */
        MimeBodyPart imgBodyPart = new MimeBodyPart(); // 附件图标
        byte[] bytes = readFile("C:/button.gif");
        ByteArrayDataSource fileds = new ByteArrayDataSource(bytes,
                "application/octet-stream");
        imgBodyPart.setDataHandler(new DataHandler(fileds));
        imgBodyPart.setFileName("button.gif");
        imgBodyPart.setHeader("Content-ID", "<img1></img1>");// 在html中使用该图片方法src="cid:IMG1"
        mp.addBodyPart(imgBodyPart);
        /** *************************************************** */
        mp.addBodyPart(bodyPart);
        mimeMessage.setContent(mp);// 设置邮件内容对象
        Transport.send(mimeMessage);// 发送邮件

    }

    /**
     * 读取文件
     * 
     * @param file
     *            文件路径
     * @return 返回二进制数组
     */
    public static byte[] readFile(String file) {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            int bytesRead;
            byte buffer[] = new byte[1024 * 1024];
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
                Arrays.fill(buffer, (byte) 0);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bos.toByteArray();
    }
}

/**
 * Smtp认证
 */
class SmtpAuthenticator extends Authenticator {
    String username = null;
    String password = null;

    // SMTP身份验证
    public SmtpAuthenticator(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.username, this.password);
    }

}
class ByteArrayDataSource implements DataSource {

    private final String contentType;
    private final byte[] buf;
    private final int len;

    public ByteArrayDataSource(byte[] buf, String contentType) {
        this(buf, buf.length, contentType);
    }

    public ByteArrayDataSource(byte[] buf, int length, String contentType) {
        this.buf = buf;
        this.len = length;
        this.contentType = contentType;
    }

    public String getContentType() {
        if (contentType == null)
            return "application/octet-stream";
        return contentType;
    }

    public InputStream getInputStream() {
        return new ByteArrayInputStream(buf, 0, len);
    }

    public String getName() {
        return null;
    }

    public OutputStream getOutputStream() {
        throw new UnsupportedOperationException();
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
Java 将图片转二进制再将二进制转成图片
importjava.awt.image.BufferedImage;importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.
Stella981 Stella981
2年前
JetBrains IDEs
importjava.io.BufferedReader;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;i
Wesley13 Wesley13
2年前
Java 操作ini文件(往ini文件中读写数据(key
importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
Java连接excel实现:通过姓名查找id和通过id查找姓名
注意每个方法结束都要关闭workbook;还有getIdbyname()方法中字符串flag与name的比较,一定要用equals()方法!!!;剩下的不多解释,注释都在代码中:importjava.io.FileInputStream;importjava.io.IOException;importjava.i
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这