List of usage examples for javax.mail.internet MimeMessage setRecipient
public void setRecipient(RecipientType type, Address address) throws MessagingException
From source file:eu.scape_project.planning.application.BugReport.java
/** * Method responsible for sending a bug report per mail. * /*from w w w .ja v a 2 s . c om*/ * @param userEmail * email address of the user. * @param errorDescription * error description given by the user. * @param exception * the exception causing the bug/error. * @param requestUri * request URI where the error occurred * @param location * the location of the application where the error occurred * @param applicationName * application name * @param plan * the plan where the exception occurred * @throws MailException * if the bug report could not be sent */ public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri, String location, String applicationName, Plan plan) throws MailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback"))); message.setSubject("[" + applicationName + "] from " + location); StringBuilder builder = new StringBuilder(); // Date builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n"); // User info if (user == null) { builder.append("No user available.\n\n"); } else { builder.append("User: ").append(user.getUsername()).append("\n"); if (user.getUserGroup() != null) { builder.append("Group: ").append(user.getUserGroup().getName()).append("\n"); } } builder.append("UserMail: ").append(userEmail).append("\n\n"); // Plan if (plan == null) { builder.append("No plan available.").append("\n\n"); } else { builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n"); builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n"); } // Description builder.append("Description:\n"); builder.append(SEPARATOR_LINE); builder.append(errorDescription).append("\n"); builder.append(SEPARATOR_LINE).append("\n"); // Request URI builder.append("Request URI: ").append(requestUri).append("\n\n"); // Exception if (exception == null) { builder.append("No exception available.").append("\n"); } else { builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n"); builder.append("Exception message: ").append(exception.getMessage()).append("\n"); StringWriter writer = new StringWriter(); exception.printStackTrace(new PrintWriter(writer)); builder.append("Stacktrace:\n"); builder.append(SEPARATOR_LINE); builder.append(writer.toString()); builder.append(SEPARATOR_LINE); } message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(), config.getString("mail.feedback")); String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."; Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO", userMessage, user); try { utx.begin(); em.persist(notification); utx.commit(); } catch (Exception e) { log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e); } } catch (MessagingException e) { throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to " + config.getString("mail.feedback"), e); } }
From source file:nl.surfnet.coin.teams.control.AddMemberController.java
/** * Sends an email based on the {@link Invitation} * * @param invitation {@link Invitation} that contains the necessary data * @param subject of the email/*www.j a v a 2 s . c o m*/ * @param inviter {@link Person} who sends the invitation * @param locale {@link Locale} for the mail */ protected void sendInvitationByMail(final Invitation invitation, final String subject, final Person inviter, final Locale locale) { final String html = composeInvitationMailMessage(invitation, inviter, locale, "html"); final String plainText = composeInvitationMailMessage(invitation, inviter, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(invitation.getEmail())); mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * /* w ww .j a v a2 s. c om*/ * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(User toUser, GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Dear " + toUser.getFullName() + ", \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n"); builder.append("Please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (Exception e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:eu.scape_project.planning.user.Groups.java
/** * Sends an invitation mail to the user. * //from ww w . j a v a2 s.c o m * @param toUser * the recipient of the mail * @param serverString * the server string * @return true if the mail was sent successfully, false otherwise * @throws InvitationMailException * if the invitation mail could not be send */ private void sendInvitationMail(GroupInvitation invitation, String serverString) throws InvitationMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(invitation.getEmail())); message.setSubject( user.getFullName() + " invited you to join the Plato group " + user.getUserGroup().getName()); StringBuilder builder = new StringBuilder(); builder.append("Hello, \n\n"); builder.append("The Plato user " + user.getFullName() + " has invited you to join the group " + user.getUserGroup().getName() + ".\n\n"); builder.append( "You do not seem to be a Plato user. If you would like to accept the invitation, please first create an account at http://" + serverString + "/idp/addUser.jsf.\n"); builder.append( "If you have an account, please log in and use the following link to accept the invitation: \n"); builder.append("http://" + serverString + "/plato/user/groupInvitation.jsf?uid=" + invitation.getInvitationActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Group invitation mail sent successfully to " + invitation.getEmail()); } catch (MessagingException e) { log.error("Error sending group invitation mail to " + invitation.getEmail(), e); throw new InvitationMailException(e); } }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpEmailFrom"); }// w w w . j a v a 2s. c o m smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:mail.MailService.java
/** * Erstellt eine MIME-Mail inkl. Transfercodierung. * @param email/*from w w w . j ava 2s.c om*/ * @throws MessagingException * @throws IOException */ public String createMail3(Mail email, Config config) throws MessagingException, IOException { byte[] mailAsBytes = email.getText(); byte[] outputBytes; // Transfercodierung anwenden if (config.getTranscodeDescription().equals(Config.BASE64)) { outputBytes = encodeBase64(mailAsBytes); } else if (config.getTranscodeDescription().equals(Config.QP)) { outputBytes = encodeQuotedPrintable(mailAsBytes); } else { outputBytes = mailAsBytes; } email.setText(outputBytes); Properties props = new Properties(); props.put("mail.smtp.host", "mail.java-tutor.com"); Session session = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(session); // msg.setHeader("MIME-Version" , "1.0"); // msg.setHeader("Content-Type" , "text/plain"); // Absender InternetAddress addressFrom = new InternetAddress(email.getAbsender()); msg.setFrom(addressFrom); // Empfnger InternetAddress addressTo = new InternetAddress(email.getEmpfaenger()); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject(email.getBetreff()); msg.setSentDate(email.getAbsendeDatum()); msg.setText(Utils.toString(outputBytes)); msg.saveChanges(); // Mail in Ausgabestrom schreiben ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { msg.writeTo(bOut); } catch (IOException e) { System.out.println("Fehler beim Schreiben der Mail in Schritt 3"); throw e; } // String out = bOut.toString(); // int pos1 = out.indexOf("Message-ID"); // int pos2 = out.indexOf("@localhost") + 13; // String output = out.subSequence(0, pos1).toString(); // output += (out.substring(pos2)); return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT, "Content-Transfer-Encoding: " + config.getTranscodeDescription())); }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser, ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpEmailFrom"); }//from ww w . jav a2 s .co m smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAst22SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:com.trivago.mail.pigeon.mail.MailFacade.java
public void sendMail(MailTransport mailTransport) { log.debug("Mail delivery started"); File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile(); Properties config = new Properties(); try {// w ww . j a va 2 s . c o m config.load(new FileReader(propertyfile)); } catch (IOException e) { log.error(e); } Session session = Session.getDefaultInstance(config); log.debug("Received session"); MimeMessage message = new MimeMessage(session); String to = mailTransport.getTo(); String from = mailTransport.getFrom(); String replyTo = mailTransport.getReplyTo(); String subject = mailTransport.getSubject(); String html = mailTransport.getHtml(); String text = mailTransport.getText(); try { Address fromAdr = new InternetAddress(from); Address toAdr = new InternetAddress(to); Address rplyAdr = new InternetAddress(replyTo); message.setSubject(subject); message.setFrom(fromAdr); message.setRecipient(Message.RecipientType.TO, toAdr); message.setReplyTo(new Address[] { rplyAdr }); message.setSender(fromAdr); message.addHeader("Return-path", replyTo); message.addHeader("X-TRV-MID", mailTransport.getmId()); message.addHeader("X-TRV-UID", mailTransport.getuId()); // Content MimeBodyPart messageTextPart = new MimeBodyPart(); messageTextPart.setText(text); messageTextPart.setContent(html, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageTextPart); // Put parts in message message.setContent(multipart); log.debug("Dispatching message"); Transport.send(message); log.debug("Mail delivery ended"); } catch (MessagingException e) { log.error(e); } }
From source file:fsi_admin.JSmtpConn.java
private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY, StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart, MimeMultipart multipart) {/*w ww . j av a 2s . c om*/ // Create a message with the specified information. try { mmsg.setFrom(new InternetAddress(FROM)); mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); mmsg.setSubject(SUBJECT); messagebodypart.setContent(BODY, MIMETYPE); multipart.addBodyPart(messagebodypart); return true; } catch (AddressException e) { e.printStackTrace(); msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage()); return false; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage()); return false; } }
From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java
private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception { URL url = new URL(uri); String recipient = url.getPath(); String server = null;//w w w.ja v a2 s .c o m String port = null; String sender = null; String subject = null; String username = null; String password = null; StringTokenizer headers = new StringTokenizer(url.getQuery(), "&"); while (headers.hasMoreTokens()) { String token = headers.nextToken(); if (token.startsWith("server=")) { server = URLDecoder.decode(token.substring("server=".length()), "UTF-8"); continue; } if (token.startsWith("port=")) { port = URLDecoder.decode(token.substring("port=".length()), "UTF-8"); continue; } if (token.startsWith("sender=")) { sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8"); continue; } if (token.startsWith("subject=")) { subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8"); continue; } if (token.startsWith("username=")) { username = URLDecoder.decode(token.substring("username=".length()), "UTF-8"); continue; } if (token.startsWith("password=")) { password = URLDecoder.decode(token.substring("password=".length()), "UTF-8"); continue; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("smtp server '" + server + "'"); if (username != null) { LOGGER.debug("smtp-auth username '" + username + "'"); } LOGGER.debug("mail sender '" + sender + "'"); LOGGER.debug("subject line '" + subject + "'"); } Properties properties = System.getProperties(); properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled())); properties.put("mail.smtp.from", sender); properties.put("mail.smtp.host", server); if (port != null) { properties.put("mail.smtp.port", port); } if (username != null) { properties.put("mail.smtp.auth", String.valueOf(true)); properties.put("mail.smtp.user", username); } Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password)); MimeMessage message = null; if (mediatype.startsWith("multipart/")) { message = new MimeMessage(session, new ByteArrayInputStream(data)); } else { message = new MimeMessage(session); if (mediatype.toLowerCase().indexOf("charset=") == -1) { mediatype += "; charset=\"" + encoding + "\""; } message.setText(new String(data, encoding), encoding); message.setHeader("Content-Type", mediatype); } message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setSentDate(new Date()); Transport.send(message); }