List of usage examples for javax.mail.internet MimeMessage addRecipient
public void addRecipient(RecipientType type, Address address) throws MessagingException
From source file:pt.ist.fenix.api.SupportFormResource.java
private void sendEmail(String from, String subject, String body, SupportBean bean) { Properties props = new Properties(); props.put("mail.smtp.host", Objects .firstNonNull(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), "localhost")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {// ww w . jav a 2s.c om message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress())); message.setSubject(subject); message.setText(body); Multipart multipart = new MimeMultipart(); { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } if (!Strings.isNullOrEmpty(bean.attachment)) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(Base64.getDecoder().decode(bean.attachment), bean.mimeType))); messageBodyPart.setFileName(bean.fileName); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); Transport.send(message); } catch (Exception e) { logger.error("Could not send support email! Original message was: " + body, e); } }
From source file:ste.xtest.mail.BugFreeFileTransport.java
private void sendSimpleMessage(String from, String to, String subject, String body) throws Exception { Session session = Session.getInstance(config); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);/*ww w . j a v a 2 s.c o m*/ message.setText(body); session.getTransport().sendMessage(message, message.getAllRecipients()); }
From source file:org.modelibra.util.Emailer.java
/** * Sends an email.//from ww w. j a v a 2s . c om * * @throws dmLite * exception if there is a problem */ public void send() throws ModelibraException { try { MimeMessage message = new MimeMessage(emailSession); InternetAddress fromIA = new InternetAddress(from); message.setFrom(fromIA); InternetAddress toIA = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toIA); message.setSubject(subject); message.setText(content); emailStore.connect(outServer, code, password); Transport.send(message); emailStore.close(); } catch (MessagingException e) { throw new ModelibraException("Could not send an email: " + e.getMessage()); } catch (IllegalStateException e) { throw new ModelibraException("Could not send an email: " + e.getMessage()); } }
From source file:org.tsm.concharto.service.EmailService.java
/** * * @param subject/*from www. ja v a 2 s . 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.apache.axis.transport.mail.MailWorker.java
/** * Send the soap request message to the server * /*from ww w . ja v a2 s .c om*/ * @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:ru.org.linux.exception.ExceptionResolver.java
/** * ? E-mail ?.//from w w w . java 2 s . c o m * * @param request ? web- * @param exception ? * @return , ? ??? ? ? */ private String sendEmailToAdmin(HttpServletRequest request, Exception exception) { InternetAddress mail; String adminEmailAddress = configuration.getAdminEmailAddress(); try { mail = new InternetAddress(adminEmailAddress, true); } catch (AddressException e) { return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress; } StringBuilder text = new StringBuilder(); if (exception.getMessage() == null) { text.append(exception.getClass().getName()); } else { text.append(exception.getMessage()); } text.append("\n\n"); Template tmpl = Template.getTemplate(request); // text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri")); String mainUrl = "<unknown>"; mainUrl = configuration.getMainUrl(); text.append("Main URL: ").append(mainUrl).append(request.getServletPath()); if (request.getQueryString() != null) { text.append('?').append(request.getQueryString()).append('\n'); } text.append('\n'); text.append("IP: " + request.getRemoteAddr() + '\n'); text.append(" Headers: "); Enumeration enu = request.getHeaderNames(); while (enu.hasMoreElements()) { String paramName = (String) enu.nextElement(); text.append("\n ").append(paramName).append(": ").append(request.getHeader(paramName)); } text.append("\n\n"); StringWriter exceptionStackTrace = new StringWriter(); exception.printStackTrace(new PrintWriter(exceptionStackTrace)); text.append(exceptionStackTrace.toString()); Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session mailSession = Session.getDefaultInstance(props, null); MimeMessage emailMessage = new MimeMessage(mailSession); try { emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru")); emailMessage.addRecipient(Message.RecipientType.TO, mail); emailMessage.setSubject("Linux.org.ru: " + exception.getClass()); emailMessage.setSentDate(new Date()); emailMessage.setText(text.toString(), "UTF-8"); } catch (Exception e) { logger.error("An error occured while creating e-mail!", e); return EMAIL_NOT_SENT; } try { Transport.send(emailMessage); return EMAIL_SENT; } catch (Exception e) { return EMAIL_NOT_SENT; } }
From source file:com.jwm123.loggly.reporter.ReportMailer.java
public void send() throws MessagingException { if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.port", config.getMailPort().toString()); props.setProperty("mail.smtp.host", config.getMailServer()); if (StringUtils.isNotBlank(config.getMailUsername()) && StringUtils.isNotBlank(config.getMailPassword())) { props.setProperty("mail.smtp.user", config.getMailUsername()); props.setProperty("mail.smtp.password", config.getMailPassword()); }/*w w w. j av a 2s . co m*/ Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) }); message.setSubject(subject); for (String recipient : recipients) { message.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } MimeMultipart containingMultipart = new MimeMultipart("mixed"); MimeMultipart messageMultipart = new MimeMultipart("alternative"); containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart)); messageMultipart.addBodyPart(newTextBodyPart(getText())); MimeMultipart htmlMultipart = new MimeMultipart("related"); htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml())); messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart)); containingMultipart.addBodyPart(addReportAttachment()); message.setContent(containingMultipart); Transport.send(message); } }
From source file:com.github.aynu.mosir.core.enterprise.mail.MailServiceImpl.java
/** * ??//from ww w . ja v a 2 s . com * @param originator * @param recipients ? * @param subject ?? * @return * @throws EnterpriseException ? */ private Message createMessage(final InternetAddress originator, final Map<RecipientType, InternetAddress> recipients, final String subject) throws EnterpriseException { Validate.isTrue(recipients.size() > 0); try { final MimeMessage message = new MimeMessage(session); if (originator != null) { message.setFrom(originator); } for (final Entry<RecipientType, InternetAddress> recipient : recipients.entrySet()) { message.addRecipient(recipient.getKey(), recipient.getValue()); } message.setSubject(subject, CHARSET); return message; } catch (final MessagingException e) { throw new EnterpriseException(e); } }
From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { String passwordDesencriptada = Desencriptar(password2); try {/*w ww. j a va 2 s .c o m*/ // Propiedades de la conexin Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("alfons018pbg@gmail.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + "")); message.setSubject("Asistencia tcnica"); message.setText("\n \n \n Estimado: " + nombre + " " + apellido + "\n El Servicio Tecnico de SEA ha recibido tu solicitud. " + "\n Los siguientes son tus datos para acceder:" + "\n Correo: " + corre + "\n Password: " + passwordDesencriptada + ""); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("alfons018pbg@gmail.com", "al12fo05zo1990"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context//from w ww . j a va 2 s. co m * * @return id for the current message * @throws Exception */ private String writeUsingSMTP(MessageContext msgContext) throws Exception { String id = (new java.rmi.server.UID()).toString(); String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST); 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; } String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS); String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message reqMessage = msgContext.getRequestMessage(); msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action); msg.setDisposition(MimePart.INLINE); msg.setSubject(id); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); reqMessage.writeTo(out); msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(fromAddress); System.out.print(client.getReplyString()); client.addRecipient(toAddress); 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(); return id; }