List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java
@Test public void testAddSecurityInfoToSubjectMismatch() throws Exception { SMIMEHandler mailet = new SMIMEHandler(); mailetConfig.setInitParameter("handledProcessor", "handled"); mailet.init(mailetConfig);/*from w ww . j a va 2s.co m*/ MockMail mail = new MockMail(); DjigzoMailAttributesImpl.getInstance(mail).setSecurityInfoTags( new SecurityInfoTags("[decrypted]", "[signed]", "[signed by: %s]", "[invalid]")); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/simple-text-body-clear-signed.eml")); message.setFrom(new InternetAddress("sender@example.com")); assertEquals("test simple message", message.getSubject()); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); assertEquals(1, sendMailEventListener.getMails().size()); Mail newMail = sendMailEventListener.getMails().get(0); assertEquals("test simple message [signed by: test@example.com]", newMail.getMessage().getSubject()); }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
@Override public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) { try {/*w w w . j a v a 2 s .c o m*/ // see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection. // following doesn't work correctly, therefore add bounce-address in message already Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"), WebappHelper.getMailConfig("mailFromName")); msg.setFrom(viewableFrom); msg.setSubject(subject, "utf-8"); // reply to can only be an address without name (at least for postfix!), see FXOLAT-312 msg.setReplyTo(new Address[] { convertedFrom }); if (tos != null && tos.length > 0) { msg.addRecipients(RecipientType.TO, tos); } if (ccs != null && ccs.length > 0) { msg.addRecipients(RecipientType.CC, ccs); } if (bccs != null && bccs.length > 0) { msg.addRecipients(RecipientType.BCC, bccs); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart("mixed"); // 1) add body part if (StringHelper.isHtml(body)) { Multipart alternativePart = createMultipartAlternative(body); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alternativePart); multipart.addBodyPart(wrap); } else { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } // 2) add attachments for (File attachmentFile : attachments) { // abort if attachment does not exist if (attachmentFile == null || !attachmentFile.exists()) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null); return msg; } BodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFile); filePart.setDataHandler(new DataHandler(source)); filePart.setFileName(attachmentFile.getName()); multipart.addBodyPart(filePart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text if (StringHelper.isHtml(body)) { msg.setContent(createMultipartAlternative(body)); } else { msg.setText(body, "utf-8"); } } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (AddressException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logError("", e); return null; } catch (UnsupportedEncodingException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }//from ww w . j a v a 2s .c om // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java
@Override public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) { return new AbstractMailSendBuilder() { @Override//ww w . ja v a 2s. c o m public void send(final String content) throws Exception { __sendExecPool.execute(new Runnable() { @Override public void run() { try { MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed()); // for (String _to : getTo()) { _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to)); } for (String _cc : getCc()) { _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc)); } for (String _bcc : getBcc()) { _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc)); } // if (getLevel() != null) { switch (getLevel()) { case LEVEL_HIGH: _message.setHeader("X-MSMail-Priority", "High"); _message.setHeader("X-Priority", "1"); break; case LEVEL_NORMAL: _message.setHeader("X-MSMail-Priority", "Normal"); _message.setHeader("X-Priority", "3"); break; case LEVEL_LOW: _message.setHeader("X-MSMail-Priority", "Low"); _message.setHeader("X-Priority", "5"); break; default: } } // String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8"); _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(), serverCfgMeta.getDisplayName(), _charset)); _message.setSubject(getSubject(), _charset); // Multipart _container = new MimeMultipart(); // MimeBodyPart _textBodyPart = new MimeBodyPart(); if (getMimeType() == null) { mimeType(IMailSender.MimeType.TEXT_PLAIN); } _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset); _container.addBodyPart(_textBodyPart); // ??<img src="cid:<CID_NAME>"> for (PairObject<String, File> _file : getAttachments()) { if (_file.getValue() != null) { MimeBodyPart _fileBodyPart = new MimeBodyPart(); FileDataSource _fileDS = new FileDataSource(_file.getValue()); _fileBodyPart.setDataHandler(new DataHandler(_fileDS)); if (_file.getKey() != null) { _fileBodyPart.setHeader("Content-ID", _file.getKey()); } _fileBodyPart.setFileName(_fileDS.getName()); _container.addBodyPart(_fileBodyPart); } } // ?? _message.setContent(_container); Transport.send(_message); } catch (Exception e) { throw new RuntimeException(RuntimeUtils.unwrapThrow(e)); } } }); } }; }
From source file:org.apache.camel.component.mail.MailBinding.java
public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange) throws MessagingException, IOException { // camel message headers takes precedence over endpoint configuration if (hasRecipientHeaders(exchange)) { setRecipientFromCamelMessage(mimeMessage, exchange); } else {//from w w w . j a v a 2s . co m // fallback to endpoint configuration setRecipientFromEndpointConfiguration(mimeMessage, endpoint); } // must have at least one recipients otherwise we do not know where to send the mail if (mimeMessage.getAllRecipients() == null) { throw new IllegalArgumentException("The mail message does not have any recipients set."); } // set the subject if it was passed in as an option in the uri. Note: if it is in both the URI // and headers the headers win. String subject = endpoint.getConfiguration().getSubject(); if (subject != null) { mimeMessage.setSubject(subject, IOConverter.getCharsetName(exchange, false)); } // append the rest of the headers (no recipients) that could be subject, reply-to etc. appendHeadersFromCamelMessage(mimeMessage, endpoint.getConfiguration(), exchange); if (empty(mimeMessage.getFrom())) { // lets default the address to the endpoint destination String from = endpoint.getConfiguration().getFrom(); mimeMessage.setFrom(new InternetAddress(from)); } // if there is an alternative body provided, set up a mime multipart alternative message if (hasAlternativeBody(endpoint.getConfiguration(), exchange)) { createMultipartAlternativeMessage(mimeMessage, endpoint.getConfiguration(), exchange); } else { if (exchange.getIn().hasAttachments()) { appendAttachmentsFromCamel(mimeMessage, endpoint.getConfiguration(), exchange); } else { populateContentOnMimeMessage(mimeMessage, endpoint.getConfiguration(), exchange); } } }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*from ww w. j av a2 s .co m*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:com.kgmp.mfds.controller.FormsController.java
@RequestMapping(value = "/updatePaymentProc.do") public ModelAndView updatePayment(@RequestParam("forms_seq") int forms_seq, @RequestParam("payment_name") String payment_name, @RequestParam("payment_bank") String payment_bank) { ModelAndView mav = new ModelAndView(); String msg = null;//from www . j a v a 2s . c om String url = null; Forms forms = new Forms(); forms.setForms_seq(forms_seq); System.out.println(payment_bank); forms.setPayment_name(payment_name); forms.setPayment_bank(payment_bank); String check = null; try { check = forms_service.updatePayment(forms); if (check.equals("yes")) { msg = "."; url = "/MyPage.do?page_seq=6"; } else { msg = "."; url = "/NewForms.do?forms_seq=" + forms_seq; } } catch (Exception e) { e.printStackTrace(); } //send payment check e-mail s try { MimeMessage message = mailSender.createMimeMessage(); String test1 = "K-GMP@K-GMP.com"; String test2 = "K-GMP@K-GMP.com"; String test3 = "STED] "; String test4 = "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'><html><body style='width:600px border:1px solid grey;'><div style='margin:0 auto; padding:10px; width:700px; border:1px solid grey;'><div> <div> <img src='http://sted.kr/resources/img/common/header_bg2.jpg' width='100%'> </div> <div style='background-color:#102967; color:#ffffff; height:30px;'> ? </div></div><div><br><br> . STED ?? .<br> <b>" + payment_name + "</b> ? .<br> ? ? ? ? ? ? .<br><br> <b>? :</b> <h1 style='color:#303698;'>" + payment_name + "</h1><br> <b> :</b> <h1 style='color:#303698;'>" + payment_bank + "</h1><br><br> ? 7? ?? ? .<br> ? 3? ?? .<br><br> ()_<a href='https://sted.kr/Admin.do'>?? </a><br><br><br> <p style='color:grey;'> ?? . ?? ? . ? ?? ? . ? ? <a href='mailto:K-GMP@K-GMP.COM'>K-GMP@K-GMP.COM</a> ?.</p><br><div style='background-color:#102967; color:#ffffff; height:30px; text-align:right;'>Copyright K-GMP All Right Reserved </div></div></div></body></html>"; message.setFrom(new InternetAddress(test1)); message.addRecipient(RecipientType.TO, new InternetAddress(test2)); message.setSubject(test3); message.setText(test4, "utf-8", "html"); mailSender.send(message); } catch (Exception e) { e.printStackTrace(); } //send e-mail e mav.addObject("msg", msg); mav.addObject("url", url); mav.setViewName("/Opener_check_proc"); return mav; }
From source file:com.flexoodb.common.FlexUtils.java
static public boolean sendMail(String host, int port, String from, String to, String subject, String msg) throws Exception { SMTPTransport transport = null;// w w w .j a v a 2 s . c om boolean ok = false; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); ok = true; } catch (Exception e) { e.printStackTrace(); } finally { try { transport.close(); } catch (Exception f) { f.printStackTrace(); } } return ok; }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject, String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException { // some timing for debug long start = 0; if (M_log.isDebugEnabled()) start = System.currentTimeMillis(); // if in test mode, use the test method if (m_testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders); return;//from w w w . j a v a 2 s . c o m } if (m_smtp == null) { M_log.error( "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties"); return; } if (from == null) { M_log.warn("sendMail: null from"); return; } if (to == null) { M_log.warn("sendMail: null to"); return; } if (content == null) { M_log.warn("sendMail: null content"); return; } Properties props = createMailSessionProperties(); Session session = Session.getInstance(props); // see if we have a message-id in the additional headers String mid = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) { // length of 'message-id: ' == 12 mid = header.substring(12); break; } } } // use the special extension that can set the id MimeMessage msg = new MyMessage(session, mid); // the FULL content-type header, for example: // Content-Type: text/plain; charset=windows-1252; format=flowed String contentTypeHeader = null; // If we need to force the container to use a certain multipart subtype // e.g. 'alternative' // then sneak it through in the additionalHeaders String multipartSubtype = null; // set the additional headers on the message // but treat Content-Type specially as we need to check the charset // and we already dealt with the message id if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": ")) contentTypeHeader = header; else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": ")) multipartSubtype = header.substring(header.indexOf(":") + 1).trim(); else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) msg.addHeaderLine(header); } } // date if (msg.getHeader(EmailHeaders.DATE) == null) msg.setSentDate(new Date(System.currentTimeMillis())); // set the message sender msg.setFrom(from); // set the message recipients (headers) setRecipients(headerTo, msg); // set the reply to if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null)) msg.setReplyTo(replyTo); // update to be Postmaster if necessary checkFrom(msg); // figure out what charset encoding to use // // first try to use the charset from the forwarded // Content-Type header (if there is one). // // if that charset doesn't work, try a couple others. // the character set, for example, windows-1252 or UTF-8 String charset = extractCharset(contentTypeHeader); if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) { // use the charset from the Content-Type header } else if (canUseCharset(content, CharacterSet.ISO_8859_1) && canUseCharset(subject, CharacterSet.ISO_8859_1)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1; charset = CharacterSet.ISO_8859_1; } else if (canUseCharset(content, CharacterSet.WINDOWS_1252) && canUseCharset(subject, CharacterSet.WINDOWS_1252)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252; charset = CharacterSet.WINDOWS_1252; } else { // catch-all - UTF-8 should be able to handle anything if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.UTF_8; else contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset=" + CharacterSet.UTF_8; charset = CharacterSet.UTF_8; } if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null)) msg.setSubject(subject, charset); // extract just the content type value from the header String contentType = null; if (contentTypeHeader != null) { int colonPos = contentTypeHeader.indexOf(":"); contentType = contentTypeHeader.substring(colonPos + 1).trim(); } setContent(content, attachments, msg, contentType, charset, multipartSubtype); // if we have a full Content-Type header, set it NOW // (after setting the body of the message so that format=flowed is preserved) // if there attachments, the messsage type will default to multipart/mixed and should // stay that way. if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) { msg.addHeaderLine(contentTypeHeader); msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable"); } if (M_log.isDebugEnabled()) { M_log.debug("HeaderLines received were: "); Enumeration<String> allHeaders = msg.getAllHeaderLines(); while (allHeaders.hasMoreElements()) { M_log.debug((String) allHeaders.nextElement()); } } sendMessageAndLog(from, to, subject, headerTo, start, msg, session); }
From source file:com.flexoodb.common.FlexUtils.java
static public String sendMailShowResult(String host, int port, String from, String to, String subject, String msg) throws Exception { String response = "OK"; SMTPTransport transport = null;/* w w w . j a v a2 s.c om*/ boolean ok = true; try { InternetAddress[] rcptto = new InternetAddress[1]; rcptto[0] = new InternetAddress(to); Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port + ""); props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original props.put("mail.smtp.timeout", "60000"); props.put("mail.smtp.quitwait", "false"); javax.mail.Session session = javax.mail.Session.getInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(msg, "text/html"); //Transport.send(message); transport.setLocalHost("REMOTE-CLIENT"); transport.connect(); transport.sendMessage(message, rcptto); } catch (Exception e) { e.printStackTrace(); ok = false; } finally { try { if (!ok) { response = "SENDING FAILED:" + transport.getLastServerResponse(); } else { response = "SENDING SUCCESS:" + transport.getLastServerResponse(); } transport.close(); } catch (Exception f) { } } return response; }