List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:eu.optimis.sm.gui.server.ServiceManagerWebServiceImpl.java
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtps.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session session = Session.getInstance(props, null); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(username + "@gmail.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); if (ccEmail.length() > 0) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); }/*from w w w . j a v a2s . c om*/ msg.setSubject(title); msg.setText(message, "utf-8"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport) session.getTransport("smtps"); t.connect("smtp.gmail.com", username, password); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
From source file:gov.nih.nci.cabig.caaers.tools.mail.CaaersJavaMailSender.java
@Override public void send(MimeMessage message) { try {// www.ja v a 2 s. c o m String fromAddress = configuration.get(Configuration.SYSTEM_FROM_EMAIL); if (!fromAddress.equals("")) message.setFrom(new InternetAddress(fromAddress)); super.send(message); } catch (MessagingException e) { throw new CaaersSystemException("Error while sending email", e); } }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context// w w w .j av a2 s. c o 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; }
From source file:com.commoncoupon.mail.EmailProcessor.java
public Integer call() throws Exception { MimeMessage message = new MimeMessage(getSession()); try {/*from w ww . j a va2 s .c o m*/ if (from != null && (from != null && from.trim() != "")) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (log.isDebugEnabled()) log.debug("Email sent from: " + sentFrom); } if (to != null && to.length > 0) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress((String) to[i]); if (log.isDebugEnabled()) log.debug("Sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null && cc.length > 0) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress((String) cc[i]); if (log.isDebugEnabled()) log.debug("Copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } message.setSentDate(new Date()); message.setSubject(subject); message.setContent(content, mimeType); Transport.send(message); } catch (Exception e) { log.error("Failed to send email.", e); return (1); } return (0); }
From source file:org.wf.dp.dniprorada.util.Mail.java
@Override public void send() throws EmailException { try {/*from w w w. ja v a 2 s. c om*/ log.info("init"); MultiPartEmail oMultiPartEmail = new MultiPartEmail(); oMultiPartEmail.setHostName(getHost()); log.info("getHost()=" + getHost()); oMultiPartEmail.addTo(getTo(), "receiver"); log.info("getTo()=" + getTo()); oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov" log.info("getFrom()=" + getFrom()); oMultiPartEmail.setSubject(getHead()); log.info("getHead()=" + getHead()); oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword()); log.info("getAuthUser()=" + getAuthUser()); log.info("getAuthPassword()=" + getAuthPassword()); oMultiPartEmail.setSmtpPort(getPort()); log.info("getPort()=" + getPort()); oMultiPartEmail.setSSL(isSSL()); log.info("isSSL()=" + isSSL()); oMultiPartEmail.setTLS(isTLS()); log.info("isTLS()=" + isTLS()); oSession = oMultiPartEmail.getMailSession(); MimeMessage oMimeMessage = new MimeMessage(oSession); //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING)); oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom())); //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING)); oMimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING)); oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING); _Attach(getBody()); oMimeMessage.setContent(oMultiparts); // oMimeMessage.getRecipients(Message.RecipientType.CC); Transport.send(oMimeMessage); log.info("[send]:Transport.send!"); } catch (Exception exc) { log.error("[send]", exc); throw new EmailException("Error happened when sending email", exc); } }
From source file:mitm.application.djigzo.ca.PFXMailBuilder.java
public MimeMessage createMessage() throws TemplateBuilderException { try {/* www. ja va 2s.com*/ checkState(); SimpleHash root = new SimpleHash(); root.put("from", from); root.put("recipient", recipient); root.put("recipientLocal", EmailAddressUtils.getLocalPart(recipient)); root.put("boundary", createBoundary()); if (properties != null) { root.putAll(properties); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); templateBuilder.buildTemplate(template, root, bos); MimeMessage templatedMessage = MailUtils.byteArrayToMessage(bos.toByteArray()); templatedMessage.setFrom(from); if (recipient != null) { templatedMessage.setRecipient(RecipientType.TO, recipient); } replacePFX(templatedMessage); /* * Make sure the message has a message-ID */ templatedMessage.saveChanges(); return templatedMessage; } catch (MessagingException e) { throw new TemplateBuilderException(e); } }
From source file:org.sigmah.server.mail.MailSenderImpl.java
@Override public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException { final String user = email.getAuthenticationUserName(); final String password = email.getAuthenticationPassword(); final Properties properties = new Properties(); properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL); properties.setProperty(MAIL_SMTP_HOST, email.getHostName()); properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort())); final StringBuilder toBuilder = new StringBuilder(); for (final String to : email.getToAddresses()) { if (toBuilder.length() > 0) { toBuilder.append(','); }/*from w ww . j a v a 2 s . c o m*/ toBuilder.append(to); } final StringBuilder ccBuilder = new StringBuilder(); if (email.getCcAddresses().length > 0) { for (final String cc : email.getCcAddresses()) { if (ccBuilder.length() > 0) { ccBuilder.append(','); } ccBuilder.append(cc); } } final Session session = javax.mail.Session.getInstance(properties); try { final DataSource attachment = new ByteArrayDataSource(fileStream, FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType()); final Transport transport = session.getTransport(); if (password != null) { transport.connect(user, password); } else { transport.connect(); } final MimeMessage message = new MimeMessage(session); // Configures the headers. message.setFrom(new InternetAddress(email.getFromAddress(), false)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false)); if (email.getCcAddresses().length > 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false)); } message.setSubject(email.getSubject(), email.getEncoding()); // Html body part. final MimeMultipart textMultipart = new MimeMultipart("alternative"); final MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\""); textMultipart.addBodyPart(htmlBodyPart); final MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(textMultipart); // Attachment body part. final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setFileName(fileName); attachmentPart.setDescription(fileName); // Mail multipart content. final MimeMultipart contentMultipart = new MimeMultipart("related"); contentMultipart.addBodyPart(textBodyPart); contentMultipart.addBodyPart(attachmentPart); message.setContent(contentMultipart); message.saveChanges(); // Sends the mail. transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException ex) { throw new EmailException( "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex); } catch (IOException ex) { throw new EmailException("An error occured while reading the attachment of an email.", ex); } catch (MessagingException ex) { throw new EmailException("An error occured while sending an email.", ex); } }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void trialCreated(String subject, String fromUser, String fromName, String toUser, InternetAddress[] toCC) {/*from w w w .j a va 2 s .com*/ Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", "http://www.uengine.io/my/license"); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/trial-created.vm", "UTF-8", model); try { InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void passwd(Long userId, String token, String subject, String fromUser, String fromName, final String toUser, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}", new Object[] { Long.toString(userId), token }).getMessage()); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model); try {//from w w w .j av a 2 s .c o m InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void registe(Long userId, String token, String subject, String fromUser, String fromName, final String toUser, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/registe/confirm?userid={}&token={}", new Object[] { Long.toString(userId), token }).getMessage()); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/registe.vm", "UTF-8", model);//from w w w. j a v a 2s.co m try { InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }