Java中使用SMTP协议发送电子邮件

本文介绍了在Java中使用SMTP协议发送电子邮件的步骤,包括获取Session对象、创建MimeMessage、设置邮件信息、添加附件以及依赖mail.jar包。示例代码展示了如何发送普通文本和HTML邮件,并提供了详细实现的身份验证方法。

Java中使用SMTP协议发送电子邮件的具体的步骤:
1、首先需要获取发送邮件的Session对象
Session session = Session.getDefaultInstance(properties,authorcator);
2、根据session对象,获取待发送的邮件消息
MimeMessage mimeMessage = new MimeMessage(session);
3、设置发件人,收件人,标题,邮件内容,附件,发送时间等;
4、利用Transport发送邮件
5、代码必须依赖与mail.jar 包
Java实现代码:
1、发送邮件,注意:该类有两个功能,一个是发送普通文本邮件;一个是发送html邮件,两者的本质是相同的,mime类型有所区别而已:

/**
 * 使用SMTP协议发送电子邮件
 */
public class SendMail{
    // 邮件发送协议
    private final static String PROTOCOL = "smtp";
    // SMTP邮件服务器
    private final static String HOST = "smtp.exmail.qq.com";
    // SMTP邮件服务器默认端口
    private final static String PORT = "25";
    // 是否要求身份认证
    private final static String IS_AUTH = "true";
    // 是否启用调试模式(启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息)
    private final static String IS_ENABLED_DEBUG_MOD = "true";
    // 发件人
    private static String from = "test_adimin@126.com";
    // 初始化连接邮件服务器的会话信息
    private static Properties props = null;

    static {
        props = new Properties();
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", IS_AUTH);
        props.setProperty("mail.debug", IS_ENABLED_DEBUG_MOD);
    }
    /**
     * 发送电子邮件
     * @param address 邮件地址
     * @param fileNames 文件名
     * @param files 文件
     * @param title 文件主题
     * @param content 文件内容
     * @throws Exception
     */
    public static void sendHtmlEmail(Address[] address, String[] fileNames,
            File[] files, String title, String content) throws Exception {
        // 创建Session实例对象
        Session session = Session.getDefaultInstance(props,new MyAuthenticator());
        // 创建邮件内容
        MimeMessage message = new MimeMessage(session);
        // 邮件主题,并指定编码格式
        message.setSubject(title, "utf-8");
        // 发件人
        message.setFrom(new InternetAddress(from));
        // 收件人
        message.setRecipients(RecipientType.BCC, address);
        // 创建一个MIME子类型为“related”的MimeMultipart对象
        MimeMultipart mp = new MimeMultipart("mixed");
        // 创建一个表示正文的MimeBodyPart对象,并将它加入到前面创建的MimeMultipart对象中
        MimeBodyPart htmlPart = new MimeBodyPart();
        mp.addBodyPart(htmlPart);
        // 将MimeMultipart对象设置为整个邮件的内容
        message.setContent(mp);
        try {
            MimeBodyPart[] mbp = new MimeBodyPart[fileNames.length];
            DataSource ds1;
            DataHandler dh1;
            for (int i = 0; i < fileNames.length; i++) {
                mbp[i] = new MimeBodyPart();
                mp.addBodyPart(mbp[i]);
                ds1 = new FileDataSource(files[i + 1]);
                dh1 = new DataHandler(ds1);
                mbp[i].setFileName(MimeUtility.encodeText(fileNames[i]));
                mbp[i].setDataHandler(dh1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建一个MIME子类型为"alternative"的MimeMultipart对象,并作为前面创建的htmlPart对象的邮件内容
        MimeMultipart htmlMultipart = new MimeMultipart("alternative");
        // 创建一个表示html正文的MimeBodyPart对象
        MimeBodyPart htmlBodypart = new MimeBodyPart();
        // 其中cid=androidlogo.gif是引用邮件内部的图片,即imagePart.setContentID("androidlogo.gif");方法所保存的图片
        htmlBodypart.setContent("<span'>" + content + "</span>","text/html;charset=utf-8");
        htmlMultipart.addBodyPart(htmlBodypart);
        htmlPart.setContent(htmlMultipart);

        // 保存并生成最终的邮件内容
        message.saveChanges();

        // 发送邮件
        Transport.send(message);

    }

    static class MyAuthenticator extends Authenticator {

        private String username = "test_adimin@126.com";

        private String password = "1";

        public MyAuthenticator() {
            super();
        }

        public MyAuthenticator(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }

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

    public static void main(String[] args) throws Exception {
        sendHtmlEmail(new Address[]{
                new InternetAddress("869095990@qq.com", "", "utf-8")},
                new String[]{"da","da"},
                new File[]{},
                "aa",
                "aa");

    }
}

2、创建身份验证:

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package javax.mail;

import java.net.InetAddress;

/**
 * @version $Rev: 467553 $ $Date: 2006-10-25 00:01:51 -0400 (Wed, 25 Oct 2006) $
 */
public abstract class Authenticator {
    private InetAddress host;
    private int port;
    private String prompt;
    private String protocol;
    private String username;

    synchronized PasswordAuthentication authenticate(InetAddress host, int port, String protocol, String prompt, String username) {
        this.host = host;
        this.port = port;
        this.protocol = protocol;
        this.prompt = prompt;
        this.username = username;
        return getPasswordAuthentication();
    }

    protected final String getDefaultUserName() {
        return username;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return null;
    }

    protected final int getRequestingPort() {
        return port;
    }

    protected final String getRequestingPrompt() {
        return prompt;
    }

    protected final String getRequestingProtocol() {
        return protocol;
    }

    protected final InetAddress getRequestingSite() {
        return host;
    }
}

另一种比较详细的详细的写法参照这个博客,写的很详细http://dove19900520.iteye.com/blog/2005303

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值