Java Code Examples for javax.mail.internet.MimeMessage#setReplyTo()

The following examples show how to use javax.mail.internet.MimeMessage#setReplyTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavamailService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
Example 2
Source File: EmailSender.java    From personal_book_library_web_project with MIT License 6 votes vote down vote up
private void transport(Session session, MailContext mailContext) throws MessagingException, UnsupportedEncodingException {
	
	MimeMessage msg = new MimeMessage(session);
	msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
	msg.addHeader("format", "flowed");
	msg.addHeader("Content-Transfer-Encoding", "8bit");

	msg.setFrom(new InternetAddress("[email protected]", "NoReply-JD"));
	msg.setReplyTo(InternetAddress.parse("[email protected]", false));

	msg.setSubject(mailContext.getTitle(), "UTF-8");
	msg.setText(mailContext.getBody(), "UTF-8");
	msg.setSentDate(new Date());
	
	msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(mailContext.getToEmails()));
	
	Transport.send(msg);
}
 
Example 3
Source File: MailHandler.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private MimeMessage getMimeMessage(MailMessage m) throws Exception {
	log.debug("getMimeMessage");
	// Building MimeMessage
	MimeMessage msg = getBasicMimeMessage();
	msg.setSubject(m.getSubject(), UTF_8.name());
	String replyTo = m.getReplyTo();
	if (replyTo != null && isMailAddReplyTo()) {
		log.debug("setReplyTo {}", replyTo);
		if (MailUtil.isValid(replyTo)) {
			msg.setReplyTo(new InternetAddress[]{new InternetAddress(replyTo)});
		}
	}
	msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(m.getRecipients(), false));

	return m.getIcs() == null ? appendBody(msg, m) : appendIcsBody(msg, m);
}
 
Example 4
Source File: EmailMessageSender.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
protected boolean sendEmail(final String subject, final String content, final String userEmailAddress,
                            final String replyTo, final String personalFromName) {
    boolean success = true;
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(userEmailAddress));
            InternetAddress[] replyTos = new InternetAddress[1];
            if ((replyTo != null) && (!"".equals(replyTo))) {
                replyTos[0] = new InternetAddress(replyTo);
                mimeMessage.setReplyTo(replyTos);
            }
            InternetAddress fromAddress = new InternetAddress(getDefaultFromAddress());
            if (personalFromName != null)
                fromAddress.setPersonal(personalFromName);
            mimeMessage.setFrom(fromAddress);
            mimeMessage.setContent(content, "text/html; charset=utf-8");
            mimeMessage.setSubject(subject);
            logger.debug("sending email to [" + userEmailAddress + "]subject subject :[" + subject + "]");
        }
    };
    try {
        if (isAuthenticatedSMTP()) {
            emailService.send(preparator);
        } else {
            emailServiceNoAuth.send(preparator);
        }
    } catch (MailException ex) {
        // simply log it and go on...
        logger.error("Error sending email notification to:" + userEmailAddress, ex);

        success = false;
    }

    return success;
}
 
Example 5
Source File: MailSession.java    From gocd with Apache License 2.0 5 votes vote down vote up
public MimeMessage createMessage(String from, String to, String subject, String body)
        throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(TO, to);
    msg.setSubject(subject);
    msg.setContent(msg, "text/plain");
    msg.setSentDate(new Date());
    msg.setText(body);
    msg.setSender(new InternetAddress(from));
    msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
    return msg;
}
 
Example 6
Source File: SpecialAddressesUtilsTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void replaceInternetAddressesShouldReturnReplyToWhenAddressesMatchReplyTo() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    message.setReplyTo(InternetAddress.parse(MailAddressFixture.ANY_AT_JAMES.toString() + ", " + MailAddressFixture.OTHER_AT_JAMES.toString()));
    FakeMail mail = FakeMail.from(message);

    MailAddress expectedReplyTo = MailAddressFixture.ANY_AT_JAMES;
    MailAddress expectedReplyTo2 = MailAddressFixture.OTHER_AT_JAMES;

    List<MailAddress> addresses = testee.replaceInternetAddresses(mail, ImmutableList.of(SpecialAddress.REPLY_TO.toInternetAddress()));

    assertThat(addresses).containsOnly(expectedReplyTo, expectedReplyTo2);
}
 
Example 7
Source File: SpecialAddressesUtilsTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void replaceMailAddressesShouldReturnReplyToWhenAddressesMatchReplyTo() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    message.setReplyTo(InternetAddress.parse(MailAddressFixture.ANY_AT_JAMES.toString() + ", " + MailAddressFixture.OTHER_AT_JAMES.toString()));
    FakeMail mail = FakeMail.from(message);

    MailAddress expectedReplyTo = MailAddressFixture.ANY_AT_JAMES;
    MailAddress expectedReplyTo2 = MailAddressFixture.OTHER_AT_JAMES;

    Collection<MailAddress> addresses = testee.replaceSpecialAddresses(mail, ImmutableList.of(SpecialAddress.REPLY_TO));

    assertThat(addresses).containsOnly(expectedReplyTo, expectedReplyTo2);
}
 
Example 8
Source File: SessionWrapper.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
public MimeMessage createMessage(String fromEmailId, String toEmailId, String subject, String body) throws MessagingException {
    MimeMessage message = new MimeMessage(instance);
    message.setFrom(new InternetAddress(fromEmailId));
    message.setRecipients(TO, toEmailId);
    message.setSubject(subject);
    message.setContent(message, "text/plain");
    message.setSentDate(new Date());
    message.setText(body);
    message.setSender(new InternetAddress(fromEmailId));
    message.setReplyTo(new InternetAddress[]{new InternetAddress(fromEmailId)});
    return message;
}
 
Example 9
Source File: Mails.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends an email synchronously.
 */
public static void send(String sender, String recipients, String subject,
		String text) throws MessagingException {
	final Properties properties = Database.query(propertySupplier);
	if (properties != null) {
		Session session = Session.getInstance(properties,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(properties
								.getProperty("mail.smtp.user", ""),
								properties.getProperty(
										"mail.smtp.password", ""));
					}
				});
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(sender));
		message.setReplyTo(new InternetAddress[] { new InternetAddress(
				sender) });
		message.setRecipients(Message.RecipientType.TO, recipients);
		message.setSubject(subject, "utf-8");
		message.setSentDate(new Date());
		message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
		message.setHeader("Content-Transfer-Encoding", "quoted-printable");
		message.setText(text, "utf-8");
		Transport.send(message);
	}
}
 
Example 10
Source File: EmailUtil.java    From journaldev with MIT License 5 votes vote down vote up
/**
 * Utility method to send simple HTML email
 * @param session
 * @param toEmail
 * @param subject
 * @param body
 */
public static void sendEmail(Session session, String toEmail, String subject, String body){
	try
    {
      MimeMessage msg = new MimeMessage(session);
      //set message headers
      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
      msg.addHeader("format", "flowed");
      msg.addHeader("Content-Transfer-Encoding", "8bit");

      msg.setFrom(new InternetAddress("[email protected]", "NoReply-JD"));

      msg.setReplyTo(InternetAddress.parse("[email protected]", false));

      msg.setSubject(subject, "UTF-8");

      msg.setText(body, "UTF-8");

      msg.setSentDate(new Date());

      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
      System.out.println("Message is ready");
   	  Transport.send(msg);  

      System.out.println("EMail Sent Successfully!!");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
}
 
Example 11
Source File: EmailFormatterOutboud.java    From matrix-appservice-email with GNU Affero General Public License v3.0 5 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, MimeMultipart body, boolean allowReply) throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(session);
    if (allowReply) {
        msg.setReplyTo(InternetAddress.parse(recvCfg.getEmail().replace("%KEY%", data.getKey())));
    }

    String sender = data.isSelf() ? sendCfg.getName() : data.getSenderName();
    msg.setFrom(new InternetAddress(sendCfg.getEmail(), sender, StandardCharsets.UTF_8.name()));
    msg.setSubject(processToken(data, template.getSubject()));
    msg.setContent(body);
    return msg;
}
 
Example 12
Source File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * sends an e-mail
 * 
 * @param session   session connection to the SMTP server
 * @param toemails  list of recipient e-mails
 * @param subject   subject (title) of the e-mail
 * @param body      body of the e-mail
 * @param fromemail origin of the e-mail
 */
private void sendEmail(Session session, String[] toemails, String subject, String body, String fromemail) {
	try {
		MimeMessage msg = new MimeMessage(session);
		// set message headers
		msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
		msg.addHeader("format", "flowed");
		msg.addHeader("Content-Transfer-Encoding", "8bit");

		msg.setFrom(new InternetAddress(fromemail));

		InternetAddress[] recipients = new InternetAddress[toemails.length];
		for (int i = 0; i < toemails.length; i++)
			recipients[i] = new InternetAddress(toemails[i]);

		msg.setReplyTo(InternetAddress.parse(fromemail, false));

		msg.setSubject(subject, "UTF-8");

		msg.setContent(body, "text/html; charset=utf-8");

		msg.setSentDate(new Date());

		msg.setRecipients(Message.RecipientType.TO, recipients);
		logger.severe("Message is ready");
		Transport.send(msg);

		logger.severe("EMail Sent Successfully!!");
	} catch (Exception e) {
		throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:"
				+ this.smtpserver + " - port:" + this.port + " - user:" + this.user);
	}
}
 
Example 13
Source File: SenderImpl.java    From live-chat-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void send(SendTask task, Props props) throws Exception {
	
	Properties sessionProps = new Properties();
	sessionProps.put("mail.smtp.auth", props.getStrVal(mail_smtp_auth));
	sessionProps.put("mail.smtp.starttls.enable", props.getStrVal(mail_smtp_starttls_enable));
	sessionProps.put("mail.smtp.host", props.getStrVal(mail_smtp_host));
	sessionProps.put("mail.smtp.port", props.getStrVal(mail_smtp_port));
	sessionProps.put("mail.debug", props.getStrVal(mail_debug));
	
	if(props.getBoolVal(mail_skipSslCertCheck)){
		sessionProps.put("mail.smtp.ssl.checkserveridentity", "false");
		sessionProps.put("mail.smtp.ssl.trust", "*");
	}

	Session session = Session.getInstance(sessionProps, new Authenticator() {

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(props.getStrVal(mail_username), props.getStrVal(mail_password));
		}
		
	});
	
	MailMsg msg = task.msg;

	MimeMessage message = new MimeMessage(session);
	message.setFrom(msg.fromEmail);
	message.setSubject(msg.subject);
	message.setText(msg.text, msg.charset, msg.subtype);
	
	Map<RecipientType, List<InternetAddress>> recipients = task.recipientGroup.byType();
	for (Entry<RecipientType, List<InternetAddress>> entry : recipients.entrySet()) {
		message.setRecipients(entry.getKey(), array(entry.getValue(), Address.class));
	}		
	
	if( ! isEmpty(msg.replyTo)){
		message.setReplyTo(array(msg.replyTo, Address.class));
	}

	Transport.send(message);

}
 
Example 14
Source File: MailSender.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public void sendMail(EmailBean emailBean) throws SendMailException {
  File tempDir = null;
  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());
      }
    }
  }
}
 
Example 15
Source File: EmailUtil.java    From Insights with Apache License 2.0 4 votes vote down vote up
public void sendEmail(Mail mail,EmailConfiguration emailConf, String emailBody) throws MessagingException,
																				IOException,UnsupportedEncodingException {

	Properties props = System.getProperties();
	props.put(EmailConstants.SMTPHOST, emailConf.getSmtpHostServer());
	props.put(EmailConstants.SMTPPORT, emailConf.getSmtpPort());
	props.put("mail.smtp.auth", emailConf.getIsAuthRequired());
	props.put("mail.smtp.starttls.enable", emailConf.getSmtpStarttlsEnable());

	// Create a Session object to represent a mail session with the specified
	// properties.
	Session session = Session.getDefaultInstance(props);
	MimeMessage msg = new MimeMessage(session);
	msg.addHeader(EmailConstants.CONTENTTYPE, EmailConstants.CHARSET);
	msg.addHeader(EmailConstants.FORMAT, EmailConstants.FLOWED);
	msg.addHeader(EmailConstants.ENCODING, EmailConstants.BIT);
	msg.setFrom(new InternetAddress(mail.getMailFrom(), EmailConstants.NOREPLY));
	msg.setReplyTo(InternetAddress.parse(mail.getMailTo(), false));
	msg.setSubject(mail.getSubject(), EmailConstants.UTF);
	msg.setSentDate(new Date());
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getMailTo(), false));
	MimeBodyPart contentPart = new MimeBodyPart();
	contentPart.setContent(emailBody, EmailConstants.HTML);

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(contentPart);

	String imageId="logoImage";
	String imagePath="/img/Insights.jpg";
	MimeBodyPart imagePart = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart);

	imageId="footerImage";
	imagePath="/img/FooterImg.jpg";
	MimeBodyPart imagePart_1 = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart_1);

	msg.setContent(multipart);

	try (Transport transport = session.getTransport();) {
		LOG.debug("Sending email...");

		transport.connect(emailConf.getSmtpHostServer(), emailConf.getSmtpUserName(),emailConf.getSmtpPassword());

		// Send the email.
		transport.sendMessage(msg, msg.getAllRecipients());
		LOG.debug("Email sent!");
	} catch (Exception ex) {
		LOG.error("Error sending email",ex);
		throw ex;
	} 

}
 
Example 16
Source File: EmailUtils.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sends an email to a given recipient for a given subject and content
 * with a {@code reply-to} header.
 *
 * @param to      The recipient of the mail ({@code to} header).
 * @param subject The subject of the mail.
 * @param text    The content of the mail.
 * @param replyTo The {@code reply-to} email header.
 * @return {@code true} if successful, {@code false} otherwise.
 */
private static boolean sendEmail(String to, String subject, String text, String replyTo) {
    final boolean emailEnabled = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAILS_ENABLED).getBoolValue();
    if (!emailEnabled) {
        logger.error("Tried to send a mail, but sending emails is disabled. Update your system settings.");
        return false;
    }

    final String smtpHost = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_HOST).getStringValue();
    final int smtpPort = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_PORT).getIntValue();
    final String emailAddress = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_ADDRESS).getStringValue();
    final String emailPassword = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_PASSWORD).getStringValue();
    final boolean debug = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.DEBUG_MODE).getBoolValue();

    try    {
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailAddress, emailPassword);
            }});

        session.setDebug(debug);
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(emailAddress));
        msg.setReplyTo(InternetAddress.parse(replyTo));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        msg.setSubject(subject);
        msg.setContent(text, "text/plain");
        msg.setSentDate(new Date());

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, smtpPort, emailAddress, emailPassword);
        Transport.send(msg);
        transport.close();

        logger.info(String.format("Mail sent: to: %s, replyTo: %s", to, replyTo));
    } catch (MessagingException messagingException) {
        logger.warn("Failed to send email.", messagingException);
        return false;
    }
    return true;
}
 
Example 17
Source File: AbstractSign.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Service does the hard work, and signs
 *
 * @param mail the mail to sign
 * @throws MessagingException if a problem arises signing the mail
 */
@Override
public void service(Mail mail) throws MessagingException {
    
    try {
        if (!isOkToSign(mail)) {
            return;
        }
        
        MimeBodyPart wrapperBodyPart = getWrapperBodyPart(mail);
        
        MimeMessage originalMessage = mail.getMessage();
        
        // do it
        MimeMultipart signedMimeMultipart;
        if (wrapperBodyPart != null) {
            signedMimeMultipart = getKeyHolder().generate(wrapperBodyPart);
        } else {
            signedMimeMultipart = getKeyHolder().generate(originalMessage);
        }
        
        MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(),
        null));
        Enumeration<String> headerEnum = originalMessage.getAllHeaderLines();
        while (headerEnum.hasMoreElements()) {
            newMessage.addHeaderLine(headerEnum.nextElement());
        }
        
        newMessage.setSender(new InternetAddress(getKeyHolder().getSignerAddress(), getSignerName()));
  
        if (isRebuildFrom()) {
            // builds a new "mixed" "From:" header
            InternetAddress modifiedFromIA = new InternetAddress(getKeyHolder().getSignerAddress(), mail.getMaybeSender().asString());
            newMessage.setFrom(modifiedFromIA);
            
            // if the original "ReplyTo:" header is missing sets it to the original "From:" header
            newMessage.setReplyTo(originalMessage.getReplyTo());
        }
        
        newMessage.setContent(signedMimeMultipart, signedMimeMultipart.getContentType());
        String messageId = originalMessage.getMessageID();
        newMessage.saveChanges();
        if (messageId != null) {
            newMessage.setHeader(RFC2822Headers.MESSAGE_ID, messageId);
        }
        
        mail.setMessage(newMessage);
        
        // marks this mail as server-signed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNING_MAILET, AttributeValue.of(this.getClass().getName())));
        // it is valid for us by definition (signed here by us)
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNATURE_VALIDITY, AttributeValue.of("valid")));
        
        // saves the trusted server signer address
        // warning: should be same as the mail address in the certificate, but it is not guaranteed
        mail.setAttribute(new Attribute(SMIMEAttributeNames.SMIME_SIGNER_ADDRESS, AttributeValue.of(getKeyHolder().getSignerAddress())));
        
        if (isDebug()) {
            LOGGER.debug("Message signed, reverse-path: {}, Id: {}", mail.getMaybeSender().asString(), messageId);
        }
        
    } catch (MessagingException me) {
        LOGGER.error("MessagingException found - could not sign!", me);
        throw me;
    } catch (Exception e) {
        LOGGER.error("Exception found", e);
        throw new MessagingException("Exception thrown - could not sign!", e);
    }
    
}
 
Example 18
Source File: SesSendNotificationHandler.java    From smart-security-camera with GNU General Public License v3.0 4 votes vote down vote up
public Parameters handleRequest(Parameters parameters, Context context) {
	context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	try {
		Session session = Session.getDefaultInstance(new Properties());
		MimeMessage message = new MimeMessage(session);
		message.setSubject(EMAIL_SUBJECT, "UTF-8");
		message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM")));
		message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) });
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT")));

		MimeBodyPart wrap = new MimeBodyPart();
		MimeMultipart cover = new MimeMultipart("alternative");
		MimeBodyPart html = new MimeBodyPart();
		cover.addBodyPart(html);
		wrap.setContent(cover);
		MimeMultipart content = new MimeMultipart("related");
		message.setContent(content);
		content.addBodyPart(wrap);

		URL attachmentURL = new URL(
				System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key());

		StringBuilder sb = new StringBuilder();
		String id = UUID.randomUUID().toString();
		sb.append("<img src=\"cid:");
		sb.append(id);
		sb.append("\" alt=\"ATTACHMENT\"/>\n");

		MimeBodyPart attachment = new MimeBodyPart();
		DataSource fds = new URLDataSource(attachmentURL);
		attachment.setDataHandler(new DataHandler(fds));

		attachment.setContentID("<" + id + ">");
		attachment.setDisposition("attachment");

		attachment.setFileName(fds.getName());
		content.addBodyPart(attachment);

		String prettyPrintLabels = parameters.getRekognitionLabels().toString();
		prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", "");
		prettyPrintLabels = prettyPrintLabels.replace(",", "<br>");
		html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "")
				+ "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID()
				+ "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb
				+ "</body></html>", "text/html");

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		message.writeTo(outputStream);
		RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
		SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);

		AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient();
		client.sendRawEmail(rawEmailRequest);

	// Convert Checked Exceptions to RuntimeExceptions to ensure that
	// they get picked up by the Step Function infrastructure
	} catch (MessagingException | IOException e) {
		throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e);
	}

	context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	return parameters;
}
 
Example 19
Source File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * sends invitation
 * 
 * @param session     session connection to the SMTP server
 * @param toemails    list of recipient e-mails
 * @param subject     invitation subject
 * @param body        invitation start
 * @param fromemail   user sending the invitation
 * @param startdate   start date of the invitation
 * @param enddate     end date of the invitation
 * @param location    location of the invitation
 * @param uid         unique id
 * @param cancelation true if this is a cancelation
 */
private void sendInvitation(Session session, String[] toemails, String subject, String body, String fromemail,
		Date startdate, Date enddate, String location, String uid, boolean cancelation) {
	try {
		// prepare mail mime message
		MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
		mimetypes.addMimeTypes("text/calendar ics ICS");
		// register the handling of text/calendar mime type
		MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
		mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");

		MimeMessage msg = new MimeMessage(session);
		// set message headers

		msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
		msg.addHeader("format", "flowed");
		msg.addHeader("Content-Transfer-Encoding", "8bit");
		InternetAddress fromemailaddress = new InternetAddress(fromemail);
		msg.setFrom(fromemailaddress);
		msg.setReplyTo(InternetAddress.parse(fromemail, false));
		msg.setSubject(subject, "UTF-8");
		msg.setSentDate(new Date());

		// set recipient

		InternetAddress[] recipients = new InternetAddress[toemails.length + 1];

		String attendeesinvcalendar = "";
		for (int i = 0; i < toemails.length; i++) {
			recipients[i] = new InternetAddress(toemails[i]);
			attendeesinvcalendar += "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
					+ toemails[i] + "\n";
		}

		recipients[toemails.length] = fromemailaddress;
		msg.setRecipients(Message.RecipientType.TO, recipients);

		Multipart multipart = new MimeMultipart("alternative");
		// set body
		MimeBodyPart descriptionPart = new MimeBodyPart();
		descriptionPart.setContent(body, "text/html; charset=utf-8");
		multipart.addBodyPart(descriptionPart);

		// set invitation
		BodyPart calendarPart = new MimeBodyPart();

		String method = "METHOD:REQUEST\n";
		if (cancelation)
			method = "METHOD:CANCEL\n";

		String calendarContent = "BEGIN:VCALENDAR\n" + method + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n"
				+ "BEGIN:VEVENT\n" + "DTSTAMP:" + iCalendarDateFormat.format(new Date()) + "\n" + "DTSTART:"
				+ iCalendarDateFormat.format(startdate) + "\n" + "DTEND:" + iCalendarDateFormat.format(enddate)
				+ "\n" + "SUMMARY:" + subject + "\n" + "UID:" + uid + "\n" + attendeesinvcalendar
				+ "ORGANIZER:MAILTO:" + fromemail + "\n" + "LOCATION:" + location + "\n" + "DESCRIPTION:" + subject
				+ "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n"
				+ "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n"
				+ "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR";

		calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
		calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
		multipart.addBodyPart(calendarPart);
		msg.setContent(multipart);
		logger.severe("Invitation is ready");
		Transport.send(msg);

		logger.severe("EMail Invitation Sent Successfully!! to " + attendeesinvcalendar);
	} catch (Exception e) {
		logger.severe(
				"--- Exception in sending invitation --- " + e.getClass().toString() + " - " + e.getMessage());
		if (e.getCause() != null)
			logger.severe(" cause  " + e.getCause().getClass().toString() + " - " + e.getCause().getMessage());
		throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:"
				+ this.smtpserver + " - port:" + this.port + " - user:" + this.user);
	}

}
 
Example 20
Source File: SendMailJob.java    From AsuraFramework with Apache License 2.0 3 votes vote down vote up
protected MimeMessage prepareMimeMessage(MailInfo mailInfo)
    throws MessagingException {
    Session session = getMailSession(mailInfo);

    MimeMessage mimeMessage = new MimeMessage(session);

    Address[] toAddresses = InternetAddress.parse(mailInfo.getTo());
    mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses);

    if (mailInfo.getCc() != null) {
        Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc());
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses);
    }

    mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom()));
    
    if (mailInfo.getReplyTo() != null) {
        mimeMessage.setReplyTo(new InternetAddress[]{new InternetAddress(mailInfo.getReplyTo())});
    }
    
    mimeMessage.setSubject(mailInfo.getSubject());
    
    mimeMessage.setSentDate(new Date());

    setMimeMessageContent(mimeMessage, mailInfo);

    return mimeMessage;
}