public static void SendMail() { final String username = Directory.userName; final String password = Directory.password; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", Directory.smtpHost); Session session = Session.getInstance( props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(Directory.fromAddress)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Directory.toAddress)); message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(Directory.ccAddress)); message.setSubject("Execution Result"); message.setText("PFA"); message.setText(MimeUtility.encodeText("Pode Has Fallen Down", "utf-8", "B")); message.setText(MimeUtility.encodeText("Fallen Down It Has", "utf-8", "B")); message.setText(MimeUtility.encodeText("It Has Fallen Down", "utf-8", "B")); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); String file = "C:/Softwares/Babu/OutputFile/" + getCurrentTime + ".zip"; String fileName = "Sample File"; DataSource source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.attachFile(file); // messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); System.out.println("Mail Sending"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private Message createMessage() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.host", host); props.setProperty("mail.smtp.port", "25"); if (useSSL) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.port", "465"); } // error:javax.mail.MessagingException: 501 Syntax: HELO hostname props.setProperty("mail.smtp.localhost", "127.0.0.1"); Session session = Session.getInstance(props, this); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(MimeUtility.encodeText(name) + "<" + name + ">")); } catch (Exception e) { logger.error(e.getMessage(), e); } return message; }
public void setSubject(String subject) { try { this.subject = MimeUtility.encodeText(subject, enc, "B"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } }
/** * Evaluate filename and client and encode appropriate disposition * * @param filename * @param request * @param response * @throws UnsupportedEncodingException */ public static void setBitstreamDisposition( String filename, HttpServletRequest request, HttpServletResponse response) { String name = filename; Matcher m = p.matcher(name); if (m.find() && !m.group().equals("")) { name = m.group(); } try { String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } finally { response.setHeader("Content-Disposition", "attachment;filename=" + name); } }
/** * 处理附件型邮件时,需要为邮件体和附件体分别创建BodyPort对象 然后将其置入MimeMultipart对象中作为一个整体进行发送 */ @Override protected void setContent(MimeMessage message) throws MailException { try { Multipart multipart = new MimeMultipart(); // 文本 BodyPart textBodyPart = new MimeBodyPart(); multipart.addBodyPart(textBodyPart); textBodyPart.setContent(text, "text/html;charset=" + charset); // 附件 for (File attachment : attachments) { BodyPart fileBodyPart = new MimeBodyPart(); multipart.addBodyPart(fileBodyPart); FileDataSource fds = new FileDataSource(attachment); fileBodyPart.setDataHandler(new DataHandler(fds)); // 中文乱码 String attachmentName = fds.getName(); fileBodyPart.setFileName(MimeUtility.encodeText(attachmentName)); } // 内容 message.setContent(multipart); } catch (Exception e) { new MailException(e.getMessage()); } }
private static String encode(final String string) { try { return string == null ? "" : MimeUtility.encodeText(string); } catch (final UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); return string; } }
public Header(String name, String value) { this.name = name; try { this.value = MimeUtility.fold(name.length() + 2, MimeUtility.encodeText(value)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to create header", e); } }
@Override public void append(final LoggingEvent event) { if (evaluator.isTriggeringEvent(event)) { try { final String subject = limitToFirstLine(String.valueOf(event.getMessage())); final String encodedSubject = MimeUtility.encodeText(subject, "UTF-8", null); msg.setSubject(encodedSubject); } catch (final UnsupportedEncodingException e) { // ??? } catch (final MessagingException e) { // ??? } } super.append(event); }
@Override public Mail send(Mail mail, MailContext ctx) { try { Session session = ctx.getSession(); Message mailMessage = new MimeMessage(session); // 设置发件人地址 Address from = new InternetAddress(ctx.getUser() + " <" + ctx.getAccount() + ">"); mailMessage.setFrom(from); // 设置所有收件人的地址 Address[] to = getAddress(mail.getReceivers()); mailMessage.setRecipients(Message.RecipientType.TO, to); // 设置抄送人地址 Address[] cc = getAddress(mail.getCcs()); mailMessage.setRecipients(Message.RecipientType.CC, cc); // 设置主题 mailMessage.setSubject(mail.getSubject()); // 发送日期 mailMessage.setSentDate(new Date()); // 构建整封邮件的容器 Multipart main = new MimeMultipart(); // 正文的body BodyPart body = new MimeBodyPart(); body.setContent(mail.getContent(), "text/html; charset=utf-8"); main.addBodyPart(body); // 处理附件 for (FileObject f : mail.getFiles()) { // 每个附件的body MimeBodyPart fileBody = new MimeBodyPart(); fileBody.attachFile(f.getFile()); // 为文件名进行转码 fileBody.setFileName(MimeUtility.encodeText(f.getSourceName())); main.addBodyPart(fileBody); } // 将正文的Multipart对象设入Message中 mailMessage.setContent(main); Transport.send(mailMessage); return mail; } catch (Exception e) { e.printStackTrace(); throw new SendMailException("发送邮件错误, 请检查邮箱配置及邮件的相关信息"); } }
/** * This method builds {@link MimeMessage} based on {@link ContentModel} * * @param fileInfo - Source file information {@link FileInfo} * @throws MessagingException */ private void buildContentModelMessage() throws MessagingException { Map<QName, Serializable> properties = messageFileInfo.getProperties(); String prop = null; setSentDate(messageFileInfo.getModifiedDate()); // Add FROM address Address[] addressList = buildSenderFromAddress(); addFrom(addressList); // Add TO address addressList = buildRecipientToAddress(); addRecipients(RecipientType.TO, addressList); prop = (String) properties.get(ContentModel.PROP_TITLE); try { prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop; prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null); } catch (UnsupportedEncodingException e) { // ignore } setSubject(prop); setContent(buildContentModelMultipart()); }
public static void send(String subject, String filePath, final Properties config) { Session session = Session.getInstance( config, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( config.getProperty("mail.userName"), config.getProperty("mail.password")); } }); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject, "UTF-8"); mimeMessage.setFrom(new InternetAddress(config.getProperty("mail.from"))); mimeMessage.setReplyTo( new Address[] {new InternetAddress(config.getProperty("mail.from"))}); mimeMessage.setRecipients( MimeMessage.RecipientType.TO, InternetAddress.parse(config.getProperty("mail.to"))); MimeMultipart mimeMultipart = new MimeMultipart("mixed"); MimeBodyPart attch1 = new MimeBodyPart(); mimeMultipart.addBodyPart(attch1); mimeMessage.setContent(mimeMultipart); DataSource ds1 = new FileDataSource(filePath); DataHandler dataHandler1 = new DataHandler(ds1); attch1.setDataHandler(dataHandler1); attch1.setFileName(MimeUtility.encodeText(FilenameUtils.getName(filePath))); mimeMessage.saveChanges(); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("MessagingException", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UnsupportedEncodingException", e); } }
public static String getContentDisposition(HttpServletRequest request, String fileName) { String contentDisposition = ""; String browser = getBrowser(request); try { if ("IE".equals(browser)) { contentDisposition = "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); } else if ("CH".equals(browser)) { contentDisposition = "attachment; filename=" + MimeUtility.encodeText(fileName, "UTF8", "B"); } else if ("SF".equals(browser)) { contentDisposition = "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } else { contentDisposition = "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); } } catch (UnsupportedEncodingException ex) { Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); } return contentDisposition; }
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws NoTypeConversionAvailableException, MessagingException, IOException { if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) { ContentType contentType = getContentType(exchange); // remove the Content-Type header. This will be wrong afterwards... exchange.getOut().removeHeader(Exchange.CONTENT_TYPE); byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph); Session session = Session.getInstance(System.getProperties()); MimeMessage mm = new MimeMessage(session); MimeMultipart mp = new MimeMultipart(multipartSubType); BodyPart part = new MimeBodyPart(); writeBodyPart(bodyContent, part, contentType); mp.addBodyPart(part); for (Map.Entry<String, Attachment> entry : exchange.getIn().getAttachmentObjects().entrySet()) { String attachmentFilename = entry.getKey(); Attachment attachment = entry.getValue(); part = new MimeBodyPart(); part.setDataHandler(attachment.getDataHandler()); part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null)); String ct = attachment.getDataHandler().getContentType(); contentType = new ContentType(ct); part.setHeader(CONTENT_TYPE, ct); if (!contentType.match("text/*") && binaryContent) { part.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); } // Set headers to the attachment for (String headerName : attachment.getHeaderNames()) { List<String> values = attachment.getHeaderAsList(headerName); for (String value : values) { part.setHeader(headerName, value); } } mp.addBodyPart(part); exchange.getOut().removeAttachment(attachmentFilename); } mm.setContent(mp); // copy headers if required and if the content can be converted into // a String if (headersInline && includeHeaders != null) { for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) { if (includeHeaders.matcher(entry.getKey()).matches()) { String headerStr = ExchangeHelper.convertToType(exchange, String.class, entry.getValue()); if (headerStr != null) { mm.setHeader(entry.getKey(), headerStr); } } } } mm.saveChanges(); Enumeration<?> hl = mm.getAllHeaders(); List<String> headers = new ArrayList<String>(); if (!headersInline) { while (hl.hasMoreElements()) { Object ho = hl.nextElement(); if (ho instanceof Header) { Header h = (Header) ho; exchange.getOut().setHeader(h.getName(), h.getValue()); headers.add(h.getName()); } } mm.saveChanges(); } mm.writeTo(stream, headers.toArray(new String[0])); } else { // keep the original data InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); IOHelper.copyAndCloseInput(is, stream); } }
public void sendEmail(String toMails, User user) throws MessagingException, UnsupportedEncodingException { GlobalSetting globalSetting = GlobalSetting.getInstance(); SecurityVerification securityVerification = securityVerificationService.findBySecurityVerificationAndType( user.getUid(), SecurityVerification.VERIFICATION_TYPE_EMAIL); if (securityVerification == null) { securityVerification = new SecurityVerification(); securityVerification.setUser(user); } Date now = Calendar.getInstance().getTime(); if (securityVerification.getCode() == null || now.getTime() - securityVerification.getVerificationTime().getTime() > securityVerification.getTimeout() * 60 * 1000) { String code = TokenUtil.getRandomString(8, 2); securityVerification.setValue(toMails); securityVerification.setCode(code); securityVerification.setStatus(SecurityVerification.VERIFICATION_STATUS_FAIL); securityVerification.setTimeout(Constants.EMAIL_TIMEOUT); securityVerification.setVerificationType(SecurityVerification.VERIFICATION_TYPE_EMAIL); securityVerification.setVerificationTime(new Date()); securityVerificationService.update(securityVerification); GlobalSetting setting = GlobalSetting.getInstance(); // 建立邮件消息 MimeMessage mailMessage = setting.getJavaMailSender().createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); // 设置收件人,寄件人 用数组发送多个邮件 messageHelper.setTo(toMails); String nick = javax.mail.internet.MimeUtility.encodeText(globalSetting.getAppName()); messageHelper.setFrom(new InternetAddress(nick + " <" + setting.getSmtpFrom() + ">")); messageHelper.setSubject(globalSetting.getSiteName() + "邮箱验证(请勿回复此邮件)"); messageHelper.setText( "<!doctype html>" + "<html>" + "<head>" + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" + "<title>祝福之风邮箱验证</title>" + "</head>" + "<body>" + "<div style='margin:0 auto;width:650px;'>" + "<h3>尊敬的用户:</h3>" + "<p>请点击以下地址,完成邮箱验证:</p>" + "<p><a href='http://" + globalSetting.getAppUrl() + "/op/security/verification/goVerifyEmail?uid=" + user.getUid() + "&code=" + URLEncoder.encode(Base64.encode(code.getBytes()), "UTF-8") + "'>http://" + globalSetting.getAppUrl() + "/op/security/verification/goVerifyEmail?uid=" + user.getUid() + "&code=" + URLEncoder.encode(Base64.encode(code.getBytes()), "UTF-8") + "</a></p>" + "<p>此链接有效期为" + Constants.EMAIL_TIMEOUT / 60 + "小时<span style='color:#808080'>(如果您无法点击此链接,请将链接复制到浏览器地址栏后访问)</span>" + "</p>" + "</div>" + "</body>" + "</html>", true); setting.getJavaMailSender().send(mailMessage); } }
public static void sendMail(String mail, MailContent mailContent) throws Exception { Properties props = new Properties(); // try { // props.load(new FileInputStream(new File("settings.properties"))); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // } props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance( props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("*****@*****.**", "mycity@123"); } }); try { String a = mail; String b = mailContent.getTopp(); String c = mailContent.getBody1(); String d = mailContent.getBody2(); Message message = new MimeMessage(session); // MimeUtility.encodeText(subject, "utf-8", "B") message.setFrom(new InternetAddress("*****@*****.**")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail)); message.setSubject(MimeUtility.encodeText(mailContent.getSubJect(), "utf-8", "B")); BodyPart body = new MimeBodyPart(); // freemarker stuff. Configuration cfg = new Configuration(); FileTemplateLoader ftl1 = new FileTemplateLoader( new File(ServletActionContext.getServletContext().getRealPath("/"))); cfg.setClassForTemplateLoading(cfg.getClass(), "/"); cfg.setTemplateLoader(ftl1); Template template = null; template = cfg.getTemplate("resources/mycity_cms/templates/mail/html-mail-template.html", "UTF-8"); Map<String, String> rootMap = new HashMap<String, String>(); rootMap.put("to", mailContent.getTopp()); rootMap.put("body1", mailContent.getBody1()); rootMap.put("body2", mailContent.getBody2()); Writer out = new StringWriter(); template.process(rootMap, out); // freemarker stuff ends. /* you can add html tags in your text to decorate it. */ // body.setContent(out.toString(), "text/html"); body.setContent(out.toString(), "text/html; charset=UTF-8"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(body); // cfg // body = new MimeBodyPart(); // // String filename = "hello.txt"; // DataSource source = new FileDataSource(filename); // body.setDataHandler(new DataHandler(source)); // body.setFileName(filename); // multipart.addBodyPart(body); // message.setContent(multipart, "text/html; charset=UTF-8;"); // Transport.send(message); } catch (MessagingException e) { LogUtility.logError(e, e.getMessage()); } System.out.println("Done...."); }
/** * 邮件发送 * * @param mailInfo * @param isHtml * @return * @throws MessagingException * @throws UnsupportedEncodingException */ private boolean send(MailSenderInfo mailInfo, boolean isHtml) throws MessagingException { // 判断是否需要身份认证 SMTPAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new SMTPAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro, authenticator); // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = null; try { from = new InternetAddress(mailInfo.getFromAddress(), mailInfo.getFromName()); } catch (UnsupportedEncodingException e) { from = new InternetAddress(mailInfo.getFromAddress()); } // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address[] to = new InternetAddress[mailInfo.getToAddress().size()]; int i = 0; for (String temp : mailInfo.getToAddress()) { to[i++] = new InternetAddress(temp); } mailMessage.setRecipients(Message.RecipientType.TO, to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 邮件对象,MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 邮件正文 BodyPart mailBody = new MimeBodyPart(); if (isHtml) { // 设置HTML内容 mailBody.setContent(mailInfo.getContent(), "text/html; charset=" + mailInfo.getCharset()); } else { // 设置非HTML内容 mailBody.setText(mailInfo.getContent()); } mainPart.addBodyPart(mailBody); // 添加邮件正文至邮件对象 // 邮件附件 for (MailAttachment item : mailInfo.getAttachFiles()) { BodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(item.getAbsoluteFile()); // 得到附件数据源 attachment.setDataHandler(new DataHandler(fds)); // 得到附件本身 // 设置文件名,并解决中文名乱码问题 String fileName = item.getAliasName(); try { attachment.setFileName(MimeUtility.encodeText(fileName)); } catch (UnsupportedEncodingException e) { attachment.setFileName(fileName); } mainPart.addBodyPart(attachment); // 添加邮件附件至邮件对象 } // 添加邮件内容对象 mailMessage.setContent(mainPart); // 保存邮件 mailMessage.saveChanges(); // 发送邮件 Transport.send(mailMessage); return true; }
/** * 发送带附件的(HTML)邮件 * * @param entity 待发送的邮件信息 */ public boolean sendAffixMail(MailSenderModel entity) { // 判断是否需要身份认证 MyAuthenticator authenticator = null; // 如果需要身份认证,则创建一个密码验证器 if (entity.isValidate()) { authenticator = new MyAuthenticator(entity.getUserName(), entity.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(entity.getProperties(), authenticator); try { // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(entity.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 // Address to = new InternetAddress(entity.getToAddress()); // Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipients( Message.RecipientType.TO, InternetAddress.parse(entity.getToAddress())); // 抄送 if (entity.getCcAddress() != null && !"".equals(entity.getCcAddress())) { mailMessage.setRecipients( Message.RecipientType.CC, InternetAddress.parse(entity.getCcAddress())); } // 暗送 if (entity.getBccAddress() != null && !"".equals(entity.getBccAddress())) { mailMessage.setRecipients( Message.RecipientType.BCC, InternetAddress.parse(entity.getBccAddress())); } // 设置邮件消息的主题 mailMessage.setSubject(entity.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); // 创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 设置HTML内容 html.setContent(entity.getContent(), "text/html; charset=" + DEFAULT_ENCODING); mainPart.addBodyPart(html); // 组装附件 MimeBodyPart file; String[] filePaths = entity.getAttachFileNames(); FileDataSource file_datasource = null; if (filePaths != null && filePaths.length > 0) { for (int i = 0; i < filePaths.length; i++) { file = new MimeBodyPart(); file_datasource = new FileDataSource(new File(filePaths[i])); DataHandler dh = new DataHandler(file_datasource); file.setDataHandler(dh); // 附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码 file.setFileName(MimeUtility.encodeText(dh.getName(), DEFAULT_ENCODING, null)); System.out.println(dh.getName()); mainPart.addBodyPart(file); } } // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); // 发送邮件 Transport.send(mailMessage); return true; } catch (MessagingException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return false; }
/** * メールを送信する * * @param fad 送信元アドレス * @param fan 送信元名 * @param tad 送信先アドレス * @param tan 送信先名 * @param tle タイトル * @param mes 本文 * @param atd 添付ファイルパス * @author kazua */ public String sendMailProc( String fad, String fan, String tad, String tan, String tle, String mes, String atd) { try { // プロパティ作成 Properties ppt = System.getProperties(); // メールパターンマッチ Pattern ptn = Pattern.compile(mailP); Matcher mc = ptn.matcher(fad); if (!mc.matches()) { return "送信元メールアドレスが異常です:" + fad; } mc = ptn.matcher(tad); if (!mc.matches()) { return "送信先メールアドレスが異常です:" + tad; } // パラメータチェック if ((tle == null || tle.equals("")) && (mes == null || mes.equals("")) && (atd == null || atd.equals(""))) { return "タイトル、本文、添付ファイルが全て未指定です"; } // SMTPアドレス設定 ppt.put("mail.smtp.host", "***.***.***.***"); // メールセッション作成 Session ssm = Session.getDefaultInstance(ppt, null); MimeMessage mms = new MimeMessage(ssm); // 送信元設定 mms.setFrom(new InternetAddress(fad, MimeUtility.encodeWord(fan, "UTF-8", "B"))); // 送信先設定 InternetAddress adr = new InternetAddress(tad, MimeUtility.encodeWord(tan, "UTF-8", "B")); mms.setRecipient(Message.RecipientType.TO, adr); // メール形式設定 mms.setHeader("Content-Type", "text/plain"); // 題名設定 if (tle != null && !tle.equals("")) { mms.setSubject(MimeUtility.encodeText(tle, "UTF-8", "B")); } // メール本体作成 MimeMultipart mmp = new MimeMultipart(); // 本文設定 if (mes != null && !mes.equals("")) { MimeBodyPart tpt = new MimeBodyPart(); tpt.setContent(mes, "text/plain; charset=\"UTF-8\""); mmp.addBodyPart(tpt); } // 添付ファイル設定 if (atd != null && !atd.equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(atd); DataHandler dhr = new DataHandler(fds); mbp.setDataHandler(dhr); mbp.setFileName(MimeUtility.encodeText(fds.getName(), "iso-2022-jp", "B")); mmp.addBodyPart(mbp); } mms.setContent(mmp); // メール送信 Transport.send(mms); return "メール送信完了"; } catch (Exception e) { return "メール送信失敗:" + e.toString(); } }
/** * Send Email. Note that content and attachments cannot be empty at the same time. * * @param smtpHost The SMTPHost. This param is needed when sending an anonymous email. When * sending normal email, the param is ignored and the default SMTPServer configured is used. * @param subject The email subject. * @param from The sender address. This address must be available in SMTPServer. * @param tos The receiver addresses. At least 1 address is valid. * @param ccs The 'copy' receiver. Can be empty. * @param bccs The 'encrypt copy' receiver. Can be empty. * @param content The email content. * @param attachments The file array represent attachments to be send. * @param isAnonymousEmail If this mail is send in anonymous mode. When set to true, the param * smtpHost is needed and sender's email address from should be in correct pattern. */ private static void sendEmail( String smtpHost, String subject, String from, String[] tos, String[] ccs, String[] bccs, String content, File[] attachments, boolean isAnonymousEmail) { // parameter check if (isAnonymousEmail && smtpHost == null) { throw new IllegalStateException( "When sending anonymous email, param smtpHost cannot be null"); } if (subject == null || subject.length() == 0) { subject = "Auto-generated subject"; } if (from == null) { throw new IllegalArgumentException("Sender's address is required."); } if (tos == null || tos.length == 0) { throw new IllegalArgumentException("At lease 1 receive address is required."); } if (content == null && (attachments == null || attachments.length == 0)) { throw new IllegalArgumentException( "Content and attachments cannot be empty at the same time"); } if (attachments != null && attachments.length > 0) { List<File> invalidAttachments = new ArrayList<File>(); for (File attachment : attachments) { if (!attachment.exists() || attachment.isDirectory() || !attachment.canRead()) { invalidAttachments.add(attachment); } } if (invalidAttachments.size() > 0) { String msg = ""; for (File attachment : invalidAttachments) { msg += "\n\t" + attachment.getAbsolutePath(); } throw new IllegalArgumentException("The following attachments are invalid:" + msg); } } Session session; Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); if (isAnonymousEmail) { // only anonymous email needs param smtpHost props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "false"); session = Session.getInstance(props, null); } else { // normal email does not need param smtpHost and uses the default host SMTPServer props.put("mail.smtp.host", SMTPServer); props.put("mail.smtp.auth", "true"); session = Session.getInstance(props, new MailAuthenticator(SMTPUsername, SMTPPassword)); } // create message MimeMessage msg = new MimeMessage(session); try { // Multipart is used to store many BodyPart objects. Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setContent(content, "text/html;charset=gb2312"); // add email content part. multipart.addBodyPart(part); // add attachment parts. if (attachments != null && attachments.length > 0) { for (File attachment : attachments) { String fileName = attachment.getName(); DataSource dataSource = new FileDataSource(attachment); DataHandler dataHandler = new DataHandler(dataSource); part = new MimeBodyPart(); part.setDataHandler(dataHandler); // solve encoding problem of attachments file name. try { fileName = MimeUtility.encodeText(fileName); } catch (UnsupportedEncodingException e) { LOGGER.error("Cannot convert the encoding of attachments file name.", e); } // set attachments the original file name. if not set, // an auto-generated name would be used. part.setFileName(fileName); multipart.addBodyPart(part); } } msg.setSubject(subject); msg.setSentDate(new Date()); // set sender msg.setFrom(new InternetAddress(from)); // set receiver, for (String to : tos) { msg.addRecipient(RecipientType.TO, new InternetAddress(to)); } if (ccs != null && ccs.length > 0) { for (String cc : ccs) { msg.addRecipient(RecipientType.CC, new InternetAddress(cc)); } } if (bccs != null && bccs.length > 0) { for (String bcc : bccs) { msg.addRecipient(RecipientType.BCC, new InternetAddress(bcc)); } } msg.setContent(multipart); // save the changes of email first. msg.saveChanges(); // to see what commands are used when sending a email, use session.setDebug(true) // session.setDebug(true); // send email Transport.send(msg); LOGGER.info("Send email success."); } catch (NoSuchProviderException e) { LOGGER.error("Email provider config error.", e); } catch (MessagingException e) { LOGGER.error("Send email error.", e); } }
/** * 发送邮件带附件 * * @author bxmen * @param user 用户名 * @param password 密码 * @param smtpHost 邮件服务器 * @param userName 发件人姓名 * @param toAddr 接收者 * @param subject 邮件主题 * @param body 邮件内容 * @param paths 文件路径 * @summary */ public void send( String user, String password, String smtpHost, String userName, String toAddr, String subject, String body, String[] paths) { try { Authenticator auth = new MailAuthenticator(user, password); Properties props = new Properties(); // 指定SMTP服务器,邮件通过它来投递 props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); // 指定发信人中文名称 if (null != userName && !userName.trim().equals("")) { msg.setFrom(new InternetAddress(user, userName)); } else { msg.setFrom(new InternetAddress(user)); } // 指定收件人,多人时用逗号分隔 InternetAddress[] tos = InternetAddress.parse(toAddr); msg.setRecipients(Message.RecipientType.TO, tos); // 标题//转码BASE64Encoder String smtpEncode = ""; if (null == smtpEncode || smtpEncode.trim().equals("")) { smtpEncode = "utf-8"; } msg.setSubject(subject, smtpEncode); Multipart multipart = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); if (body != null && !body.equals("")) { mimeBodyPart.setText(body, "GBK"); } else { mimeBodyPart.setText(new String(), "GBK"); } multipart.addBodyPart(mimeBodyPart); // 在第二部分信息中附加文件 if (paths != null) { for (int i = 0; i < paths.length; i++) { // 得到文件路径 String path = paths[i]; // 获取文件名称 String fileName = path.substring(path.lastIndexOf("/") + 1, path.length()); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); FileDataSource fds = new FileDataSource(CommonConstants.ROOTPATH + paths[i]); mimeBodyPart2.setDataHandler(new DataHandler(fds)); mimeBodyPart2.setFileName(MimeUtility.encodeText(fileName)); multipart.addBodyPart(mimeBodyPart2); } } // 增加 Multipart 到信息体 msg.setContent(multipart); msg.setSentDate(new Date()); Transport transport = session.getTransport("smtp"); transport.send(msg); } catch (MessagingException e) { if (DEBUG) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { if (DEBUG) { e.printStackTrace(); } } }