---
title: "使用SUN的MAIL包发邮件"
author: "thtwin"
date: "2010-03-11T09:02:57Z"
tags: ["SUN"]
categories: ["编程语言"]
slug: "sun-mail"
draft: false
lastmod: "2010-03-11T09:02:57Z"
id: 612719
url: "https://thtwin.iteye.com/blog/612719"
---

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailTester {

    public static void main(String args) throws Exception {
        // 发送者相关参数
        String host = "smtp.163.com";
        // 发件者邮箱
        String from = "xxx@163.com";
        // 发送者登陆服务器时的用户名
        String username = "xxx";
        // 发送者登陆服务器时的密码
        String password = "xxx";
        // 接收者邮箱
        String to = "yyy@163.com";
        // 邮件主题
        String subject = "javaMail发送的主题";
        // 邮件内容
        String mailConent = "这是netjavasender发送的邮件内容,你收到么？　";
        JavaMailTester jm = new JavaMailTester();
        jm.sendMail(host, from, username, password, to, subject, mailConent);

    }

    /**
     * 通过SMTP的邮件发送方法
     * 
     * @param host
     *            :发送时所使用的smtp服务器
     * @param from
     *            : 发送者名字
     * @param username
     *            : 发送者登陆服务器时的用户名
     * @param password
     *            : 发送者登陆服务器时的密码
     * @param to
     *            :接收者邮箱
     * @param subject
     *            : 邮件主题
     * @param mailConent
     *            ：邮件内容
     * @return :是否发送成功
     */
    public boolean sendMail(String host, String from, String username,
            String password, String to, String subject, String mailConent)
            throws Exception {
        // 创建一个参数表
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        // 服务器需要认证
        props.put("mail.smtp.auth", "true");
        // 得到邮件发送对象
        Session session = Session.getDefaultInstance(props);
        // 输出调试信息
        session.setDebug(true);
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setText(mailConent);
        // 使用smtp协议发送邮件
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        System.out.println("己发送成功.........");
        return true;
    }
}