List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:com.sangupta.jerry.email.service.impl.SmtpEmailServiceImpl.java
/** * @see com.sangupta.jerry.email.service.EmailService#sendEmail(com.sangupta.jerry.email.domain.Email) *///from w w w .j av a2s . c om @Override public boolean sendEmail(final Email email) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { if (AssertUtils.isNotEmpty(email.getTo())) { for (EmailAddress address : email.getTo()) { mimeMessage.setRecipient(RecipientType.TO, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getCc())) { for (EmailAddress address : email.getCc()) { mimeMessage.setRecipient(RecipientType.CC, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getBcc())) { for (EmailAddress address : email.getBcc()) { mimeMessage.setRecipient(RecipientType.BCC, address.getInternetAddress()); } } if (AssertUtils.isNotEmpty(email.getReplyTo())) { Address[] replyTo = new Address[email.getReplyTo().size()]; int counter = 0; for (EmailAddress address : email.getReplyTo()) { replyTo[counter++] = address.getInternetAddress(); } mimeMessage.setReplyTo(replyTo); } mimeMessage.setFrom(email.getFrom().getInternetAddress()); mimeMessage.setSubject(email.getSubject()); mimeMessage.setContent(email.getText(), "text/html; charset=utf-8"); } }; try { this.mailSender.send(preparator); return true; } catch (MailException e) { LOGGER.error("Unable to send email", e); } return false; }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java
/** * Sends an email to the given id including a link to the password page. The * link contains the refID./*from w ww.ja va 2 s.c o m*/ * * @param emailType * - refers to the email that shall be sent, 0 sends an email for * newly registered users, 1 sends a standard password-reset * email * @param emailaddress * @param refID * @return */ public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) { String salutation = ""; if (user.getGender().equalsIgnoreCase("male")) { salutation = "geehrter Herr " + user.getName(); } else { salutation = "geehrte Frau " + user.getName(); } MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"), emailProperties.getProperty("mail.user.password")); // Login Properties props = (Properties) emailProperties.clone(); props.remove("mail.user"); props.remove("mail.user.password"); Session session = Session.getInstance(props, auth); String htmlContent = emailBody; htmlContent = htmlContent.replaceFirst("TITLE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".title")); htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT", emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject")); htmlContent = htmlContent.replaceFirst("HEADER1", emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1")); htmlContent = htmlContent.replaceFirst("MESSAGE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".message")); htmlContent = htmlContent.replaceFirst("SALUTATION", salutation); htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); htmlContent = htmlContent.replaceFirst("REFERER", refID); htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'"); htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'"); String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - " + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n" + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"); textContent = textContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); textContent = textContent.replaceFirst("REFERER", refID); textContent = textContent.replaceFirst("SALUTATION", salutation); textContent = textContent.replaceAll("<br>", "\n"); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress()); msg.setSentDate(new Date()); msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject")); Multipart mp = new MimeMultipart("alternative"); // plaintext MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(textContent); mp.addBodyPart(textPart); // html MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); MimeBodyPart imagePart = new MimeBodyPart(); DataSource fds = null; try { fds = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart.setDataHandler(new DataHandler(fds)); imagePart.setHeader("Content-ID", "header-image"); mp.addBodyPart(imagePart); MimeBodyPart imagePart2 = new MimeBodyPart(); DataSource fds2 = null; try { fds2 = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.dash")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart2.setDataHandler(new DataHandler(fds2)); imagePart2.setHeader("Content-ID", "dash"); mp.addBodyPart(imagePart2); msg.setContent(mp); Transport.send(msg); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); return false; } return true; }
From source file:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;// w w w. j ava 2 s . c o m try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java
public void sendEmail(String subject, String text, String toEmail) { // Recipient's email ID needs to be mentioned. String to = toEmail;/*from w w w . j ava2s . c om*/ // Sender's email ID needs to be mentioned String from = "flimplatereader@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties // Properties properties = System.getProperties(); Properties properties = System.getProperties(); // Setup mail server //properties.setProperty("mail.smtp.host", "10.101.3.229"); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.setProperty("mail.user", "flimplatereader"); properties.setProperty("mail.password", "flimimages"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); //enable authentication final String pww = "flimimages"; Session session; session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(text); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w w w. j a v a2s .com*/ * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) { try {//from w ww . j ava2 s .co m Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); msg.setFrom(from); msg.setSubject(subject, "utf-8"); if (to != null) { msg.addRecipient(RecipientType.TO, to); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart(); // 1) add body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); // 2) add attachments for (DBMailAttachment attachment : attachments) { // abort if attachment does not exist if (attachment == null || attachment.getSize() <= 0) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null); return msg; } messageBodyPart = new MimeBodyPart(); VFSLeaf data = getAttachmentDatas(attachment); DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text msg.setText(body, "utf-8"); } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (MessagingException e) { logError("", e); return null; } }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
@Test public void testEncryptPDFFromPersonalUTF8() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); PDFEncrypt mailet = new PDFEncrypt(); mailetConfig.setInitParameter("template", "encrypted-pdf.ftl"); mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor"); mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor"); mailetConfig.setInitParameter("passwordMode", "single"); mailetConfig.setInitParameter("passThrough", "false"); mailet.init(mailetConfig);//w ww . ja v a 2s .c om MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml")); message.setFrom(new InternetAddress("test@example.com", "=?UTF-8?B?w6TDtsO8IMOEw5bDnA==?=")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("m.brinkers@pobox.com")); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("sender@example.com")); // password is test when encrypted with password 'djigzo' new DjigzoMailAttributesImpl(mail).setEncryptedPassword(Base64.decodeBase64(MiscStringUtils .toAsciiBytes("lklfx6SWxIkAAAAQ1VTbMJjznNZjVvdggckSPQAACAAAAAAQKAxcw630UmyVhyZPiW9xhg=="))); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testEncryptPDFFromPersonalUTF8", listener.getMessages()); assertEquals(1, listener.getMessages().size()); assertEquals("encryptedProcessor", listener.getStates().get(0)); assertEquals(2, listener.getRecipients().get(0).size()); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("123@example.com"))); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.brinkers@pobox.com"))); assertEquals("sender@example.com", listener.getSenders().get(0).toString()); assertEquals(Mail.GHOST, mail.getState()); assertNotNull(listener.getMessages().get(0)); assertTrue(message != listener.getMessages().get(0)); MimeMessage encrypted = listener.getMessages().get(0); assertTrue(encrypted.isMimeType("multipart/mixed")); Multipart mp = (Multipart) encrypted.getContent(); assertEquals(2, mp.getCount()); BodyPart messagePart = mp.getBodyPart(0); BodyPart pdfPart = mp.getBodyPart(1); assertTrue(messagePart.isMimeType("text/plain")); assertTrue(pdfPart.isMimeType("application/pdf")); // check if the body contains (which is the decoded from personal name) String text = (String) messagePart.getContent(); assertTrue(text.contains(" ")); MailUtils.validateMessage(listener.getMessages().get(0)); }
From source file:mitm.application.djigzo.james.mailets.PDFEncryptTest.java
@Test public void testReplyInvalidFrom() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); Mailet mailet = new PDFEncrypt(); String template = FileUtils.readFileToString(new File("test/resources/templates/pdf-attachment.ftl")); autoTransactDelegator.setGlobalProperty("pdfTemplate", template); autoTransactDelegator.setGlobalProperty("user.serverSecret", "123", true /* encrypt */); autoTransactDelegator.setGlobalProperty("user.pdf.replyAllowed", "true"); autoTransactDelegator.setGlobalProperty("user.pdf.replyURL", "http://127.0.0.1"); autoTransactDelegator.setProperty("m.brinkers@pobox.com", "user.pdf.replyAllowed", "true"); mailetConfig.setInitParameter("log", "starting"); mailetConfig.setInitParameter("template", "encrypted-pdf.ftl"); mailetConfig.setInitParameter("templateProperty", "pdfTemplate"); mailetConfig.setInitParameter("encryptedProcessor", "encryptedProcessor"); mailetConfig.setInitParameter("notEncryptedProcessor", "notEncryptedProcessor"); mailetConfig.setInitParameter("passwordMode", "multiple"); mailet.init(mailetConfig);/* w w w . j av a 2 s.c o m*/ MockMail mail = new MockMail(); mail.setState(Mail.DEFAULT); Passwords passwords = new Passwords(); PasswordContainer container = new PasswordContainer("test", "test ID"); passwords.put("m.brinkers@pobox.com", container); new DjigzoMailAttributesImpl(mail).setPasswords(passwords); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/normal-message-with-attach.eml")); message.setFrom(new InternetAddress("&*^&*^&*", false)); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("m.bRINKERs@pobox.com")); mail.setRecipients(recipients); mail.setSender(null); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); TestUtils.saveMessages(tempDir, "testUserTemplateEncryptPDF", listener.getMessages()); assertEquals(1, listener.getMessages().size()); assertEquals("encryptedProcessor", listener.getStates().get(0)); assertEquals(1, listener.getRecipients().get(0).size()); assertTrue(listener.getRecipients().get(0).contains(new MailAddress("m.bRINKERs@pobox.com"))); assertNull(listener.getSenders().get(0)); assertEquals(Mail.DEFAULT, mail.getState()); message = listener.getMessages().get(0); assertNotNull(message); MailUtils.validateMessage(message); checkEncryption(message, "test", false); }
From source file:org.gcaldaemon.core.GmailEntry.java
public final void send(String to, String cc, String bcc, String subject, String memo, boolean html) throws Exception { MimeMessage mimeMessage = new MimeMessage(smtpSession); // Add 'to' fields StringTokenizer st = new StringTokenizer(to, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.TO, st.nextToken()); }/* w w w.j a v a 2 s . co m*/ // Add 'cc' fields if (cc != null && cc.length() != 0) { st = new StringTokenizer(cc, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.CC, st.nextToken()); } } // Add 'bcc' fields if (bcc != null && bcc.length() != 0) { st = new StringTokenizer(bcc, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.BCC, st.nextToken()); } } // Set message if (html) { mimeMessage.setHeader("Content-Type", "text/html"); mimeMessage.setContent(memo.trim(), "text/html; charset=UTF-8"); } else { mimeMessage.setHeader("Content-Type", "text/plain"); mimeMessage.setContent(memo.trim(), "text/plain; charset=UTF-8"); } // Set 'from', 'subject' and date fields mimeMessage.setFrom(new InternetAddress(username)); mimeMessage.setSubject(subject.trim(), "UTF-8"); mimeMessage.setSentDate(new Date()); Transport.send(mimeMessage); }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Send xml data/*from w w w. java 2 s . c om*/ * * @param String purpose of this email * @param String file to send * @param String mime type * @param String subject of email * @param String header of mail * @param boolean compress data if true */ public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header, boolean compressData) throws EmailSendException { try { log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType); if (fileToSend != null && fileToSend.exists()) { InternetAddress[] toAddresses = getToAddressList(); Properties props = new Properties(); if (smtpServerAddress != null) { log.debug("sendData:smtp address: " + smtpServerAddress); props.setProperty("mail.smtp.host", smtpServerAddress); } Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject == null ? "" : subject); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); ByteArrayDataSource dataSrc = null; String fileName = fileToSend.getName(); if (compressData) { log.debug("Sending compressed data"); dataSrc = compressFile(fileToSend); dataSrc.setName(fileName + ".gz"); messageBodyPart.setFileName(fileName + ".gz"); } else { log.debug("Sending uncompressed data:"); dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType); message.setContent(FileUtils.readFileToString(fileToSend), "text/html"); multipart = null; } String headerToSend = null; if (header == null) { headerToSend = ""; } messageBodyPart.setHeader("helium-bld-data", headerToSend); messageBodyPart.setDataHandler(new DataHandler(dataSrc)); if (multipart != null) { multipart.addBodyPart(messageBodyPart); // add to the // multipart message.setContent(multipart); } try { message.setFrom(getFromAddress()); } catch (AddressException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } catch (LDAPException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } message.addRecipients(Message.RecipientType.TO, toAddresses); log.info("Sending email alert: " + subject); Transport.send(message); } } catch (MessagingException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } throw new EmailSendException(fullErrorMessage, e); } catch (IOException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } // We are Ignoring the errors as no need to fail the build. throw new EmailSendException(fullErrorMessage, e); } }