服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用javamail发送邮件

/**
 * copyright_2006, liao xuefeng
 * created on 2006-4-7
 */
package com.crackj2ee.util.mail;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class simplemailsender {

    public static void main(string[] arge) throws exception {
        string from = "
abc_abc_abc@163.com";
        string to = "xyz_xyz_xyz
@163.com";
        string subject = "test mail";
        string body = "a text mail";
        properties props = system.getproperties();
        // 设置smtp邮件服务器:
        props.put("mail.smtp.host", "smtp.163.com");
        // smtp服务器需要验证:
        props.put("mail.smtp.auth", "true");
        // 传入用户名和口令:
        session session = session.getdefaultinstance(props,
                new passwordauthenticator("your_username", "your_password"));
        // 创建新邮件:
        message msg = new mimemessage(session);
        msg.setfrom(new internetaddress(from));
        msg.setrecipients(message.recipienttype.to, internetaddress.parse(to, false));
        msg.setsubject(subject);
        msg.settext(body);
        msg.setsentdate(new date());
        // 发送:
        transport.send(msg);
    }
}

class passwordauthenticator extends authenticator {

    private string username;
    private string password;

    public passwordauthenticator(string username, string password) {
        this.username = username;
        this.password = password;
    }

    protected passwordauthentication getpasswordauthentication() {
        return new passwordauthentication(username, password);
    }

}

扫描关注微信公众号