SendMail


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

public class SendMail {

    private String host;
    private String user;
    private String password;

    public SendMail() {
    }

    public void send(String to, String subject, String body) throws Exception {
        Properties props = new Properties();
        Session sendMailSession;
        Transport transport;
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host); //smtp主机名。
        props.put("mail.smtp.user", user); //发送方邮件地址。
        props.put("mail.smtp.password", password); //邮件密码。
        PopupAuthenticator popA = new PopupAuthenticator(); //邮件安全认证。
        int index = user.indexOf("@");
        String userName = user.substring(0, index);
        PasswordAuthentication pop = popA.performCheck(userName, password); //填写用户名及密码
        sendMailSession = Session.getInstance(props, popA);
        Message newMessage = new MimeMessage(sendMailSession);
        newMessage.setFrom(new InternetAddress(user));
        newMessage.setRecipient(Message.RecipientType.TO,
                                new InternetAddress(to)); //接收方邮件地址
        newMessage.setSubject(subject);
        newMessage.setSentDate(new Date());
        newMessage.setText(body); //邮件正文
        transport = sendMailSession.getTransport("smtp");
        transport.send(newMessage);
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public class PopupAuthenticator extends Authenticator {
        String username = null;
        String password = null;
        public PopupAuthenticator() {}

        public PasswordAuthentication performCheck(String user, String pass) {
            username = user;
            password = pass;
            return getPasswordAuthentication();
        }

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

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值