java 发送邮件

package com.email;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailTemplate {
      
    private String title;
    private String content;
    private String signature;
    private String[] emails;
      
      
    public EmailTemplate(String title,String content,String signature,String[] emails){
        this.title = title;
        this.content = content;
        this.emails = emails;
        this.signature = signature;
    }
      
    public boolean sendEmailToStu(){
        Properties pros = new Properties();
        pros.setProperty("mail.smtp.auth", "true");  //设置登录为true
        pros.setProperty("mail.transport.protocol", "smtp"); //设置通信协议为smtp
        pros.setProperty("mail.host", "smtp.sina.com");        //设置发件主机
        //会话采用的用户名密码
        Session session = Session.getInstance(pros,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("[email protected]", "jsjxgb");
                }
            }  
        );
        //在命令行打印调试信息
        //session.setDebug(true);
        //创建邮件
        Message msg = new MimeMessage(session);
        //设置发件人
        try {
            msg.setFrom(new InternetAddress("[email protected]"));
            //设置主题
            msg.setSubject(title);
            //设置内容,格式和编码
            String emailContent = "<center><font size='+4' style='color:#F00'>" + this.title + "</font></center>同学你好:<br />" +
                    "<p>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + this.content + "</p><p align='right'>" + this.signature + "</p>";
            msg.setContent(emailContent,"text/html;charset=gbk");
            String sendEmail = "";
            for(String s:emails){
                sendEmail = sendEmail + s +",";
            }
            sendEmail = sendEmail.substring(0,sendEmail.length()-1);
            //设定收件人
            msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(sendEmail));
            //发送邮件
            Transport.send(msg,InternetAddress.parse(sendEmail));
        } catch (AddressException e) {
            return false;
            //  e.printStackTrace();
        } catch (MessagingException e) {
            return false;
            //e.printStackTrace();
        }
        return true;
    }
      
    public static void main(String[] args) {
        new EmailTemplate("title","content","signature",new String[]{"[email protected]"}).sendEmailToStu();
    }
}


你可能感兴趣的:(java,代码,邮件,import)