Java发送邮件

来源:互联网 发布:淘宝号怎么升级快 编辑:程序博客网 时间:2024/05/21 18:47

1.引入javax.mail.jar

public class MailTool {
    
    private final static Log log = LogFactory.getLog(MailTool.class);                                   
     public static void sendEmail(String host, String from, String to, String username, String password, String subject, String mailText) throws AddressException, MessagingException {
            // Get system properties
            Properties props = new Properties();
            // Setup mail server
            props.put("mail.smtp.host", host);
            //发送邮件时是否以授权方式访问邮件服务器
            props.put("mail.smtp.auth", "true");
            MyAuthenticator myauth = new MyAuthenticator(username, password);
            //Session session = Session.getDefaultInstance(props, myauth);
            Session session = Session.getInstance(props, myauth);
            //如果需要在发送邮件过程中监控mail命令的话,可以在发送前设置debug标志
            // Define message
            MimeMessage message = new MimeMessage(session);
          
                // Set the from address
                message.setFrom(new InternetAddress(from));
                // Set the to address
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                // Set the subject
                message.setSubject(subject, "gb2312");
                //用于存储邮件体(包括正文与附件)
                /*Multipart multipart = new MimeMultipart();
                //--创建邮件正文
                // Create the message part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailText, "text/html;charset=gb2312");
                multipart.addBodyPart(messageBodyPart);*/
            /*
             * 邮件头(参见RFC822,RFC2047)只能包含US-ASCII字符。邮件头中任何包含非US-ASCII字符
             * 的部分必须进行编码,使其只包含US-ASCII字符。所以使用java mail发送中文邮件必须经过编
             * 码,否则别人收到你的邮件只能是乱码一堆。不过使用java mail 包的解决方法很简单,用它自
             * 带的MimeUtility工具中encode开头的方法(如encodeText)对中文信息进行编码就可以了。
             */
                message.setContent(mailText, "text/html;charset=gb2312");
             
                message.saveChanges(); // implicit with send()
                log.info(message.getFrom());
                Transport transport = session.getTransport("smtp");
                transport.connect(host, username, password);
                transport.sendMessage(message, message.getAllRecipients());
                 
                transport.close();
           
        }
}
class MyAuthenticator extends javax.mail.Authenticator {
    private String strUser;
    private String strPwd;

    public MyAuthenticator(String user, String password) {
        this.strUser = user;
        this.strPwd = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(strUser, strPwd);
    }
}

0 0
原创粉丝点击