1 packagecom.smtp;2
3 importjava.util.Date;4 importjava.util.Enumeration;5 importjava.util.Properties;6 importjava.util.Vector;7
8 importjavax.activation.DataHandler;9 importjavax.activation.FileDataSource;10 importjavax.mail.Authenticator;11 importjavax.mail.Message;12 importjavax.mail.MessagingException;13 importjavax.mail.Multipart;14 importjavax.mail.PasswordAuthentication;15 importjavax.mail.Session;16 importjavax.mail.Transport;17 importjavax.mail.internet.InternetAddress;18 importjavax.mail.internet.MimeBodyPart;19 importjavax.mail.internet.MimeMessage;20 importjavax.mail.internet.MimeMultipart;21 importjavax.mail.internet.MimeUtility;22
23 public classSendMail {24
25 publicString toChinese(String text) {26 try{27 text = MimeUtility.encodeText(new String(text.getBytes(), "GB2312"), "GB2312", "B");28 } catch(Exception e) {29 e.printStackTrace();30 }31 returntext;32 }33
34 public booleansendMail(MailBean mb) {35 String host =mb.getHost();36 final String username =mb.getUsername();37 final String password =mb.getPassword();38 String from =mb.getFrom();39 String to =mb.getTo();40 String subject =mb.getSubject();41 String content =mb.getContent();42 String fileName =mb.getFilename();43 Vector file =mb.getFile();44
45 Properties props =System.getProperties();46 props.put("mail.smtp.host", host); //设置SMTP的主机
47 props.put("mail.smtp.auth", "true"); //需要经过验证
48
49 Session session = Session.getInstance(props, newAuthenticator() {50 publicPasswordAuthentication getPasswordAuthentication() {51 return newPasswordAuthentication(username, password);52 }53 });54
55 try{56 MimeMessage msg = newMimeMessage(session);57 msg.setFrom(newInternetAddress(from));58 InternetAddress[] address = { newInternetAddress(to) };59 msg.setRecipients(Message.RecipientType.TO, address);60 msg.setSubject(toChinese(subject));61
62 Multipart mp = newMimeMultipart();63 MimeBodyPart mbpContent = newMimeBodyPart();64 mbpContent.setText(content);65 mp.addBodyPart(mbpContent);66
67 /*往邮件中添加附件*/
68 if (file != null) {69 Enumeration efile =file.elements();70 while(efile.hasMoreElements()) {71 MimeBodyPart mbpFile = newMimeBodyPart();72 fileName =efile.nextElement().toString();73 FileDataSource fds = newFileDataSource(fileName);74 mbpFile.setDataHandler(newDataHandler(fds));75 mbpFile.setFileName(toChinese(fds.getName()));76 mp.addBodyPart(mbpFile);77 }78 System.out.println("添加成功");79 }80
81 msg.setContent(mp);82 msg.setSentDate(newDate());83 Transport.send(msg);84
85 } catch(MessagingException me) {86 me.printStackTrace();87 return false;88 }89 return true;90 }91
92 }