List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java
private void sendEmail(String sender, String recipient, String subject, String text) { try {//from w w w . ja v a2 s . c om Properties props = System.getProperties(); props.put("mail.smtp.port", "" + smtpPort); props.put("mail.smtp.socketFactory.port", "" + smtpPort); if (ssl) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); } if (smtpUser != null) { props.put("mail.smtp.auth", "true"); } Session session = Session.getInstance(props, null); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sender)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false)); msg.setSubject(subject); msg.setText(text, Constants.UTF_8); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); t.connect(smtpHost, smtpUser, smtpPassword); t.sendMessage(msg, msg.getAllRecipients()); t.close(); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java
@Override public void send(String senderAddress, String senderName, String recipient, String content) { if (StringUtils.isBlank(senderAddress)) { throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " + "You must set a value for notifications to work"); }//w w w . j a v a2 s. c om if (StringUtils.isBlank(content)) { throw new InternalServerError("Notification content is empty"); } try { InternetAddress sender = new InternetAddress(senderAddress, senderName); MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8)); msg.setHeader("X-Mailer", "mxisd"); // FIXME set version msg.setSentDate(new Date()); msg.setFrom(sender); msg.setRecipients(Message.RecipientType.TO, recipient); msg.saveChanges(); log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.setStartTLS(cfg.getTls() > 0); transport.setRequireStartTLS(cfg.getTls() > 1); log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort()); transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword()); try { transport.sendMessage(msg, InternetAddress.parse(recipient)); log.info("Invite to {} was sent", recipient); } finally { transport.close(); } } catch (UnsupportedEncodingException | MessagingException e) { throw new RuntimeException("Unable to send e-mail invite to " + recipient, e); } }
From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java
@Test public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException { MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties())); msg.setFrom(new InternetAddress("alert@srotya.com")); msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com")); msg.setSubject("test mail"); msg.setContent("Hello", "text/html"); Transport.send(msg);// ww w. j av a 2s .c o m MailService ms = new MailService(); ms.init(new HashMap<>()); Alert alert = new Alert(); alert.setBody("test"); alert.setId((short) 0); alert.setMedia("test"); alert.setSubject("test"); alert.setTarget("alert@srotya.com"); ms.sendMail(alert); assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize()); System.err.println("Mail sent"); }
From source file:cc.kune.core.server.mail.MailServiceDefault.java
@Override public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body, final boolean isHtml, final String... tos) { if (smtpSkip) { return;//from www . j av a 2 s.co m } // Get session final Session session = Session.getDefaultInstance(props, null); // Define message final MimeMessage message = new MimeMessage(session); for (final String to : tos) { try { message.setFrom(new InternetAddress(from)); // In case we should use utf8 also in address: // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // If additional header should be added // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B")); final String formatedSubject = subject.getString(); message.setSubject(formatedSubject, "utf-8"); final String formatedBody = body.getString(); if (isHtml) { // message.setContent(formatedBody, "text/html"); message.setText(formatedBody, "UTF-8", "html"); } else { message.setText(formatedBody, "UTF-8"); } // Send message Transport.send(message); } catch (final AddressException e) { } catch (final MessagingException e) { final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s", from, subject, to); log.error(error, e); // Better not to throw exceptions because users emails can be wrong... // throw new DefaultException(error, e); } } }
From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format)./* www. j a v a 2 s .c om*/ * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }
From source file:org.apache.axis.transport.mail.MailWorker.java
/** * Send the soap request message to the server * //from www . jav a 2 s .c o m * @param msgContext * @param smtpHost * @param sendFrom * @param replyTo * @param output * @throws Exception */ private void writeUsingSMTP(MessageContext msgContext, String smtpHost, String sendFrom, String replyTo, String subject, Message output) throws Exception { SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(sendFrom)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(replyTo)); msg.setDisposition(MimePart.INLINE); msg.setSubject(subject); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); output.writeTo(out); msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(sendFrom); System.out.print(client.getReplyString()); client.addRecipient(replyTo); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); }
From source file:org.tsm.concharto.service.EmailService.java
/** * * @param subject/*from w w w .ja va2s . c om*/ * @param body * @param sender * @param recipients */ public void SendIndividualMessages(String subject, String body, InternetAddress sender, String[] recipients) { int emailErrorCount = 0; for (int i = 0; i < recipients.length; i++) { String recipientEmailAddress = recipients[i]; MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); try { message.setText(body); message.setSubject(subject); message.setFrom(sender); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress)); sendMessage(message); } catch (Exception e) { log.error(e.getMessage(), e); emailErrorCount++; } } if (emailErrorCount > 0) { String message = emailErrorCount + " out of " + recipients.length + " emails could not be sent."; log.error(message); } }
From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java
protected void sendmail0(Map<String, Object> mail) throws MessagingException, IOException, TemplateException, LoginException, RenderingException { Session session = getSession();/*from w ww . j a v a 2 s . c o m*/ if (javaMailNotAvailable || session == null) { log.warn("Not sending email since JavaMail is not configured"); return; } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); context.put("Runtime", Framework.getRuntime()); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); }
From source file:org.georchestra.console.mailservice.Email.java
protected void sendMsg(String msg) throws AddressException, MessagingException { if (LOG.isDebugEnabled()) { LOG.debug("body: " + msg); }/* w ww.j a v a 2s . co m*/ // Replace {publicUrl} token with the configured public URL msg = msg.replaceAll("\\{publicUrl\\}", this.georConfig.getProperty("publicUrl")); final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", smtpHost); session.getProperties().setProperty("mail.smtp.port", (new Integer(smtpPort)).toString()); final MimeMessage message = new MimeMessage(session); if (isValidEmailAddress(from)) { message.setFrom(new InternetAddress(from)); } boolean validRecipients = false; for (String recipient : recipients) { if (isValidEmailAddress(recipient)) { validRecipients = true; message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } if (!validRecipients) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(from)); message.setSubject("[ERREUR] Message non dlivr : " + subject, subjectEncoding); } else { message.setSubject(subject, subjectEncoding); } if (msg != null) { /* See http://www.rgagnon.com/javadetails/java-0321.html */ if ("true".equalsIgnoreCase(emailHtml)) { message.setContent(msg, "text/html; charset=" + bodyEncoding); } else { message.setContent(msg, "text/plain; charset=" + bodyEncoding); } LOG.debug(msg); } Transport.send(message); LOG.debug("email has been sent to:\n" + Arrays.toString(recipients)); }
From source file:com.anteam.alert.email.service.EmailAntlert.java
@Override public boolean send(AntlertMessage antlertMsg) { MimeMessage mimeMsg; // MIME // from?to?/*from w w w . ja v a 2 s. c om*/ mimeMsg = new javax.mail.internet.MimeMessage(mailSession); try { // ? mimeMsg.setFrom(sender); // mimeMsg.setRecipients(RecipientType.TO, receivers); // mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET); // MimeBodyPart messageBody = new MimeBodyPart(); messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBody); mimeMsg.setContent(multipart); // ?? mimeMsg.setSentDate(new Date()); mimeMsg.saveChanges(); // ?? Transport.send(mimeMsg); } catch (MessagingException e) { logger.error("???", e); return false; } return true; }