List of usage examples for javax.mail.internet MimeMessage setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object//from w w w .j av a 2 s.c o m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:hudson.tasks.MailSender.java
private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException, UnsupportedEncodingException { MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession()); // TODO: I'd like to put the URL to the page in here, // but how do I obtain that? msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName()); msg.addHeader("X-Jenkins-Result", build.getResult().toString()); msg.setContent("", "text/plain"); msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset)); msg.setSentDate(new Date()); String replyTo = Mailer.descriptor().getReplyToAddress(); if (StringUtils.isNotBlank(replyTo)) { msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) }); }/* www . j a v a2 s . c om*/ Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>(); String defaultSuffix = Mailer.descriptor().getDefaultSuffix(); StringTokenizer tokens = new StringTokenizer(recipients); while (tokens.hasMoreTokens()) { String address = tokens.nextToken(); if (address.startsWith("upstream-individuals:")) { // people who made a change in the upstream String projectName = address.substring("upstream-individuals:".length()); AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(), AbstractProject.class); if (up == null) { listener.getLogger().println("No such project exist: " + projectName); continue; } includeCulpritsOf(up, build, listener, rcp); } else { // ordinary address // if not a valid address (i.e. no '@'), then try adding suffix if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) { address += defaultSuffix; } try { rcp.add(Mailer.StringToAddress(address, charset)); } catch (AddressException e) { // report bad address, but try to send to other addresses listener.getLogger().println("Unable to send to address: " + address); e.printStackTrace(listener.error(e.getMessage())); } } } for (AbstractProject project : includeUpstreamCommitters) { includeCulpritsOf(project, build, listener, rcp); } if (sendToIndividuals) { Set<User> culprits = build.getCulprits(); if (debug) listener.getLogger() .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)==" + culprits.size()); rcp.addAll(buildCulpritList(listener, culprits)); } msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()])); AbstractBuild<?, ?> pb = build.getPreviousBuild(); if (pb != null) { MailMessageIdAction b = pb.getAction(MailMessageIdAction.class); if (b != null) { msg.setHeader("In-Reply-To", b.messageId); msg.setHeader("References", b.messageId); } } return msg; }
From source file:com.buzzdavidson.spork.client.OWAClient.java
/** * Fetch the body of the email message given a message URL. * * @param message Mime message to add body to * @param messageUrl URL of message (OWA WebDav) *//*from ww w. java 2s . com*/ private void populateMessage(MimeMessage message, String messageUrl) { GetMethod get = new GetMethod(messageUrl); get.setRequestHeader("Translate", "F"); try { logger.info("Requesting message body via url [" + messageUrl + "]"); int status = client.executeMethod(get); if (logger.isDebugEnabled()) { logger.debug("Message request returned status code [" + status + "]"); } if (status == HttpStatus.SC_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream())); String contentType = OWAUtils.getSingleHeader(message, PARAM_CONTENT_TYPE); String contentEncoding = OWAUtils.getSingleHeader(message, PARAM_CONTENT_ENCODING); boolean needContentType = (contentType == null || contentType.length() < 1); // first set of entries are headers, followed by empty line. skip to first empty line. for (String line; (line = in.readLine()) != null;) { if (line != null && line.trim().length() == 0) { break; } } StringBuffer buf = new StringBuffer(); for (String line; (line = in.readLine()) != null;) { buf.append(line); buf.append(NEWLINE); } if (needContentType || contentType.contains(CONTENT_TYPE_TEXT_PLAIN)) { // OWA sometimes reports XML or HTML content as "text/plain"; check for this. if (logger.isDebugEnabled()) { logger.debug("checking content encoding"); } byte[] blob = buf.toString().getBytes(); if (logger.isDebugEnabled()) { logger.debug("blob length is " + blob.length + " bytes"); } if (contentEncoding.equals(BASE_64_ENCODING)) { if (logger.isDebugEnabled()) { logger.debug("blob is base64 encoded, decoding"); } byte[] newblob = Base64.decodeBase64(blob); if (logger.isDebugEnabled()) { logger.debug("decoded blob length is " + newblob.length + " bytes"); } String data = new String(newblob); buf = new StringBuffer(data); } else { if (logger.isDebugEnabled()) { logger.debug("blob is encoded with [" + contentEncoding + "], not decoding"); } } contentType = determineContentType(buf, message); } if (wantDiagnostics) { buf.append(NEWLINE); buf.append("-------------------------------------"); buf.append(NEWLINE); buf.append("SPORK Data"); buf.append(NEWLINE); buf.append("content-encoding: " + contentEncoding); buf.append(NEWLINE); buf.append("content-type: " + contentType); if (needContentType) { buf.append(" (calculated) " + contentType); buf.append(" Message processed " + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date())); } } if (needContentType) { buf = cleanupBuffer(buf); } buf.append(NEWLINE); message.setText(buf.toString()); int len = buf.length(); message.setHeader(PARAM_CONTENT_LENGTH, Integer.valueOf(len).toString()); // close enough :) if (contentType != null && contentType.length() > 0) { message.setHeader(PARAM_CONTENT_TYPE, contentType); } message.saveChanges(); } } catch (HttpException ex) { logger.error("Received HttpException fetching message body", ex); } catch (UnsupportedEncodingException ex) { logger.error("Received UnsupportedEncodingException fetching message body", ex); } catch (IOException ex) { logger.error("Received IOException fetching message body", ex); } catch (MessagingException ex) { logger.error("Received MessagingException fetching message body", ex); } }
From source file:com.sonicle.webtop.mail.Service.java
public Message reply(MailAccount account, MimeMessage orig, boolean replyToAll, boolean fromSent) throws MessagingException { MimeMessage reply = new MimeMessage(account.getMailSession()); /*//ww w . j av a 2 s . c om * Have to manipulate the raw Subject header so that we don't lose * any encoding information. This is safe because "Re:" isn't * internationalized and (generally) isn't encoded. If the entire * Subject header is encoded, prefixing it with "Re: " still leaves * a valid and correct encoded header. */ String subject = orig.getHeader("Subject", null); if (subject != null) { if (!subject.regionMatches(true, 0, "Re: ", 0, 4)) { subject = "Re: " + subject; } reply.setHeader("Subject", subject); } Address a[] = null; if (!fromSent) a = orig.getReplyTo(); else { Address ax[] = orig.getRecipients(RecipientType.TO); if (ax != null) { a = new Address[1]; a[0] = ax[0]; } } reply.setRecipients(Message.RecipientType.TO, a); if (replyToAll) { Vector v = new Vector(); Session session = account.getMailSession(); // add my own address to list InternetAddress me = InternetAddress.getLocalAddress(session); if (me != null) { v.addElement(me); } // add any alternate names I'm known by String alternates = null; if (session != null) { alternates = session.getProperty("mail.alternates"); } if (alternates != null) { eliminateDuplicates(v, InternetAddress.parse(alternates, false)); } // should we Cc all other original recipients? String replyallccStr = null; boolean replyallcc = false; if (session != null) { replyallcc = PropUtil.getBooleanSessionProperty(session, "mail.replyallcc", false); } // add the recipients from the To field so far eliminateDuplicates(v, a); a = orig.getRecipients(Message.RecipientType.TO); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { if (replyallcc) { reply.addRecipients(Message.RecipientType.CC, a); } else { reply.addRecipients(Message.RecipientType.TO, a); } } a = orig.getRecipients(Message.RecipientType.CC); a = eliminateDuplicates(v, a); if (a != null && a.length > 0) { reply.addRecipients(Message.RecipientType.CC, a); } // don't eliminate duplicate newsgroups a = orig.getRecipients(MimeMessage.RecipientType.NEWSGROUPS); if (a != null && a.length > 0) { reply.setRecipients(MimeMessage.RecipientType.NEWSGROUPS, a); } } String msgId = orig.getHeader("Message-Id", null); if (msgId != null) { reply.setHeader("In-Reply-To", msgId); } /* * Set the References header as described in RFC 2822: * * The "References:" field will contain the contents of the parent's * "References:" field (if any) followed by the contents of the parent's * "Message-ID:" field (if any). If the parent message does not contain * a "References:" field but does have an "In-Reply-To:" field * containing a single message identifier, then the "References:" field * will contain the contents of the parent's "In-Reply-To:" field * followed by the contents of the parent's "Message-ID:" field (if * any). If the parent has none of the "References:", "In-Reply-To:", * or "Message-ID:" fields, then the new message will have no * "References:" field. */ String refs = orig.getHeader("References", " "); if (refs == null) { // XXX - should only use if it contains a single message identifier refs = orig.getHeader("In-Reply-To", " "); } if (msgId != null) { if (refs != null) { refs = MimeUtility.unfold(refs) + " " + msgId; } else { refs = msgId; } } if (refs != null) { reply.setHeader("References", MimeUtility.fold(12, refs)); } //try { // setFlags(answeredFlag, true); //} catch (MessagingException mex) { // // ignore it //} return reply; }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null; boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null;/*from ww w . jav a 2 s . c om*/ //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email) throws MessagingException { if (url == null) { return false; } else if (!Core.hasOutputSMTP()) { return false; } else if (!Core.hasAdminEmail()) { return false; } else if (!Domain.isEmail(email)) { return false; } else if (NoReply.contains(email, true)) { return false; } else {/* www. j a v a 2 s. c om*/ try { Server.logDebug("sending unblock by e-mail."); User user = User.get(email); InternetAddress[] recipients; if (user == null) { recipients = InternetAddress.parse(email); } else { recipients = new InternetAddress[1]; recipients[0] = user.getInternetAddress(); } Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminInternetAddress()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Chave de desbloqueio SPFBL"; } else { subject = "Unblocking key SPFBL"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); if (locale.getLanguage().toLowerCase().equals("pt")) { buildConfirmAction(builder, "Desbloquear IP", url, "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net", "http://spfbl.net/"); } else { buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL", "SPFBL.net", "http://spfbl.net/en/"); } builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL"); buildText(builder, "Se voc o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:"); } else { buildMessage(builder, "Unblock of IP " + ip + " at DNSBL"); buildText(builder, "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:"); } buildText(builder, "<a href=\"" + url + "\">" + url + "</a>"); buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 30000); } catch (MailConnectException ex) { throw ex; } catch (SendFailedException ex) { throw ex; } catch (MessagingException ex) { throw ex; } catch (Exception ex) { Server.logError(ex); return false; } } }
From source file:net.spfbl.http.ServerHTTP.java
public static boolean enviarOTP(Locale locale, User user) { if (locale == null) { Server.logError("no locale defined."); return false; } else if (!Core.hasOutputSMTP()) { Server.logError("no SMTP account to send TOTP."); return false; } else if (!Core.hasAdminEmail()) { Server.logError("no admin e-mail to send TOTP."); return false; } else if (user == null) { Server.logError("no user definied to send TOTP."); return false; } else if (NoReply.contains(user.getEmail(), true)) { Server.logError("cannot send TOTP because user is registered in noreply."); return false; } else {// www . j ava 2 s.c o m try { Server.logDebug("sending TOTP by e-mail."); String secret = user.newSecretOTP(); InternetAddress[] recipients = new InternetAddress[1]; recipients[0] = user.getInternetAddress(); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminInternetAddress()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Chave TOTP do SPFBL"; } else { subject = "SPFBL TOTP key"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { buildMessage(builder, "Sua chave <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> no sistema SPFBL em " + Core.getHostname()); buildText(builder, "Carregue o QRCode abaixo em seu Google Authenticator ou em outro aplicativo <a target=\"_blank\" href=\"http://spfbl.net/totp/\">TOTP</a> de sua preferncia."); builder.append(" <div id=\"divcaptcha\">\n"); builder.append(" <img src=\"cid:qrcode\"><br>\n"); builder.append(" "); builder.append(secret); builder.append("\n"); builder.append(" </div>\n"); } else { buildMessage(builder, "Your <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> key in SPFBL system at " + Core.getHostname()); buildText(builder, "Load QRCode below on your Google Authenticator or on other application <a target=\"_blank\" href=\"http://spfbl.net/en/totp/\">TOTP</a> of your choice."); builder.append(" <div id=\"divcaptcha\">\n"); builder.append(" <img src=\"cid:qrcode\"><br>\n"); builder.append(" "); builder.append(secret); builder.append("\n"); builder.append(" </div>\n"); } buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Making QRcode part. MimeBodyPart qrcodePart = new MimeBodyPart(); String code = "otpauth://totp/" + Core.getHostname() + ":" + user.getEmail() + "?" + "secret=" + secret + "&" + "issuer=" + Core.getHostname(); File qrcodeFile = Core.getQRCodeTempFile(code); qrcodePart.attachFile(qrcodeFile); qrcodePart.setContentID("<qrcode>"); qrcodePart.addHeader("Content-Type", "image/png"); qrcodePart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); content.addBodyPart(qrcodePart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. boolean sent = Core.sendMessage(message, 5000); qrcodeFile.delete(); return sent; } catch (Exception ex) { Server.logError(ex); return false; } } }
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarDesbloqueio(String url, String remetente, String destinatario) throws SendFailedException, MessagingException { if (url == null) { return false; } else if (!Core.hasOutputSMTP()) { return false; } else if (!Domain.isEmail(destinatario)) { return false; } else if (NoReply.contains(destinatario, true)) { return false; } else {//from www. ja v a 2s .co m try { Server.logDebug("sending unblock by e-mail."); Locale locale = User.getLocale(destinatario); InternetAddress[] recipients = InternetAddress.parse(destinatario); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminEmail()); message.setReplyTo(InternetAddress.parse(remetente)); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Solicitao de envio SPFBL"; } else { subject = "SPFBL send request"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); buildMessage(builder, subject); if (locale.getLanguage().toLowerCase().equals("pt")) { buildText(builder, "Este e-mail foi gerado pois nosso servidor recusou uma ou mais mensagens do remetente " + remetente + " e o mesmo requisitou que seja feita a liberao para que novos e-mails possam ser entregues a voc."); buildText(builder, "Se voc deseja receber e-mails de " + remetente + ", acesse o endereo abaixo e para iniciar o processo de liberao:"); } else { buildText(builder, "This email was generated because our server has refused one or more messages from the sender " + remetente + " and the same sender has requested that the release be made for new emails can be delivered to you."); buildText(builder, "If you wish to receive emails from " + remetente + ", access the address below and to start the release process:"); } buildText(builder, "<a href=\"" + url + "\">" + url + "</a>"); buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 5000); } catch (MailConnectException ex) { throw ex; } catch (SendFailedException ex) { throw ex; } catch (MessagingException ex) { throw ex; } catch (Exception ex) { Server.logError(ex); return false; } } }
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarConfirmacaoDesbloqueio(String destinatario, String remetente, Locale locale) { if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isEmail(remetente) && !NoReply.contains(remetente, true)) { try {//from ww w. jav a2 s .c o m Server.logDebug("sending unblock confirmation by e-mail."); InternetAddress[] recipients = InternetAddress.parse(remetente); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminEmail()); message.setReplyTo(InternetAddress.parse(destinatario)); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Confirmao de desbloqueio SPFBL"; } else { subject = "SPFBL unblocking confirmation"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); buildMessage(builder, subject); if (locale.getLanguage().toLowerCase().equals("pt")) { buildText(builder, "O destinatrio '" + destinatario + "' acabou de liberar o recebimento de suas mensagens."); buildText(builder, "Por favor, envie novamente a mensagem anterior."); } else { buildText(builder, "The recipient '" + destinatario + "' just released the receipt of your message."); buildText(builder, "Please send the previous message again."); } buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 5000); } catch (MessagingException ex) { return false; } catch (Exception ex) { Server.logError(ex); return false; } } else { return false; } }
From source file:net.spfbl.spf.SPF.java
private static boolean enviarLiberacao(String url, String remetente, String destinatario) { if (Core.hasOutputSMTP() && Core.hasAdminEmail() && Domain.isValidEmail(remetente) && Domain.isValidEmail(destinatario) && url != null && !NoReply.contains(remetente, true)) { try {//from ww w . j a v a 2 s .c o m Server.logDebug("sending liberation by e-mail."); Locale locale = Core.getDefaultLocale(remetente); InternetAddress[] recipients = InternetAddress.parse(remetente); Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminEmail()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Liberao de recebimento"; } else { subject = "Receiving release"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); ServerHTTP.loadStyleCSS(builder); builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); ServerHTTP.buildMessage(builder, subject); if (locale.getLanguage().toLowerCase().equals("pt")) { ServerHTTP.buildText(builder, "O recebimento da sua mensagem para " + destinatario + " est sendo atrasado por suspeita de SPAM."); ServerHTTP.buildText(builder, "Para que sua mensagem seja liberada, acesse este link e resolva o desafio reCAPTCHA:"); } else { ServerHTTP.buildText(builder, "Receiving your message to " + destinatario + " is being delayed due to suspected SPAM."); ServerHTTP.buildText(builder, "In order for your message to be released, access this link and resolve the reCAPTCHA:"); } ServerHTTP.buildText(builder, "<a href=\"" + url + "\">" + url + "</a>"); ServerHTTP.buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = ServerHTTP.getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 5000); } catch (MailConnectException ex) { return false; } catch (SendFailedException ex) { return false; } catch (Exception ex) { Server.logError(ex); return false; } } else { return false; } }