【JavaEE】经典JAVA EE企业应用实战-读书笔记7

来源:互联网 发布:考研不考数学知乎 编辑:程序博客网 时间:2024/06/07 13:44

使用JavaMail发送邮件的步骤如下

1)创建邮件Session实例

2)以Session实例为参数创建MimeMessage对象

3)为MimeMessage对象设置合适的属性和内容

4)使用抽象类TransportsendsendMessage方法发送邮件

public class SendMail{//收件人邮箱地址private String to;//发件人邮箱地址private String from;//SMTP服务器地址private String smtpServer;//登录SMTP服务器的用户名private String username;//登录SMTP服务器的密码private String password;//邮件主题private String subject;//邮件正文private String content;//记录所有附件的集合List<String> attachments=new ArrayList<String>();//无参数的构造器public SendMail(){}//所有属性的构造器(不包括附件的集合)public SendMail(...){...}//省略set和get方法...//把邮件主题转换为中文public String transferChinese(String strText){try{strText=MimeUtility.encodeText(new String(strText.getBytes(),”GB2313”,”B”));}catch(Exception e){e.printStackTraces();}return strText;}//增加附件,将附件文件名添加到List集合中public void attachfile(String fname){attachments.add(fname);}//发送邮件public boolean send(){//创建邮件Session所需的Properties对象Properties props=new Properties();props.put(“mail.smtp.host”,smtpServer);props.put(“mail.smtp.auth”,”true”);//创建Session对象Session session=Session.getDefaultInstance(props,//创建登录服务器的认证对象new Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(username,password);}});try{//构造MimeMessage并设置相关属性值MimeMessage msg=new MimeMessage(session);//设置发件人msg.setForm(new InternetAddress(form));//设置收件人InternetAddress[] addresses={new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO,addresses);//设置邮件主题subject=transferChinese(subject);msg.setSubject(subject);//构造MultipartMultipart mp=new MimeMultipart();//向Multipart添加正文MimeBodyPart mbpContent=new MimeBodyPart();mdpContent.setText(content);//将BodyPart添加到Multipart容器中mp.addBodyPart(mbpContent);//向Multipart添加附件//遍历附件列表,将所有文件添加到邮件消息里for(String efile:attachments){MimeBodyPart mbpFile=new MimeBodyPart();//以文件名创建FileDataSource对象FileDataSource fds=new FileDataSource(efile);//处理附件mbpFile.setDataHandler(new DataHandler(fds));mbpFile.setFileName(fds.getName());//将BodyPart添加到Multipart容器中mp.addBodyPart(mbpFile);}//清空附件列表attachments.clear();//向Multipart添加MimeMessagemsg.setContent(mp);//设置发送日期msg.setSentDate(new Date());//发送邮件Transport.send(msg);}catch(MessagingException mex){mex.printStackTrace();return false;}        return true;        }public static void main(String[] args){SendMail sendMail=new SendMail();...sendMail.attachfile(“src/A.java”);sendMail.attachfile(“build.xml”);if(sendMail.send()){System.out.println(“发送成功”);}}}
上面程序在创建Session时,使用Authenticator的匿名内部类完成SMTP的认证。少数邮件服务器在使用SMTP服务时无需安全认证,即可如下

  Properties props=new Properties();

  props.put(“mail.smtp.host”,smtpServer);

  props.put(“mail.smtp.auth”,”false”);

  Session session=Session.getDafaultInstance(props);

调用MimeMessage对象的setRecipients方法,第一个参数用于指定发送发送。取值如下

  Message.RecipientType.BCC:暗抄

  Message.RecipientType.CC:抄送

  Message.RecipientType.TO:普通发送

0 0
原创粉丝点击