List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:com.pinterest.deployservice.email.SMTPMailManagerImpl.java
public void send(String to, String title, String message) throws Exception { Session session = Session.getDefaultInstance(properties, getAuthenticator()); // Create a default MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From: header field of the header. mimeMessage.setFrom(new InternetAddress(adminAddress)); // Set To: header field of the header. mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field mimeMessage.setSubject(title);// w ww. j av a 2s .c o m // Now set the actual message mimeMessage.setText(message); // Send message Transport.send(mimeMessage); }
From source file:com.local.ask.controller.mail.MailManagerImpl.java
@Override public void confirmRegistration(UserTemp userTemp) { try {// ww w . j av a 2 s .co m MimeMessage message = mailSender.createMimeMessage(); message.setSubject("Local Ask - Confirm Registration"); message.setFrom(new InternetAddress("local.ask.com@gmail.com")); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(userTemp.getEmail()); String text; text = template.replace("{displayName}", userTemp.getDisplayName()) .replace("{email}", userTemp.getEmail()).replace("{id}", userTemp.getConfirmCode()); helper.setText(text, true); mailSender.send(message); } catch (MessagingException ex) { Logger.getLogger(MailManagerImpl.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.lf.yydp.service.film.BuyTicketService.java
/** * :?/* w w w . ja v a2s . c om*/ * @param receiver */ public void sendEmail(String receiver) { Properties p = null; InputStream inputSteam = null; String senter = null; String Subject = null; String Content = null; try { p = new Properties(); inputSteam = BuyTicketService.class.getClassLoader().getResourceAsStream("mail.properties"); p.load(inputSteam); final String uname = p.getProperty("mail.uname"); final String license = p.getProperty("mail.license"); senter = p.getProperty("mail.senter"); Subject = p.getProperty("mail.subject"); Content = p.getProperty("mail.content"); Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uname, license); } }; Session session = Session.getInstance(p, authenticator); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senter)); msg.setRecipient(RecipientType.TO, new InternetAddress(receiver)); msg.setSubject(Subject); msg.setContent(Content, "text/html;charset=utf-8"); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputSteam != null) { inputSteam.close(); } } catch (Exception e2) { e2.printStackTrace(); } } }
From source file:org.mobicents.servlet.restcomm.email.EmailService.java
EmailResponse send(final Mail mail) { try {//from ww w .j a v a 2 s . co m InternetAddress from; if (mail.from() != null || !mail.from().equalsIgnoreCase("")) { from = new InternetAddress(mail.from()); } else { from = new InternetAddress(user); } final InternetAddress to = new InternetAddress(mail.to()); final MimeMessage email = new MimeMessage(session); email.setFrom(from); email.addRecipient(Message.RecipientType.TO, to); email.setSubject(mail.subject()); email.setText(mail.body()); email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false)); email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false)); Transport.send(email); return new EmailResponse(mail); } catch (final MessagingException exception) { logger.error(exception.getMessage(), exception); return new EmailResponse(exception, exception.getMessage()); } }
From source file:de.blizzy.documentr.mail.SubscriptionMailer.java
private void sendMail(String subject, String text, String senderEmail, String senderName, Set<String> subscriberEmails, JavaMailSender sender) { for (String subscriberEmail : subscriberEmails) { try {//from w ww . ja v a 2s.com MimeMessage msg = sender.createMimeMessage(); msg.setFrom(createAddress(senderEmail, senderName)); msg.setRecipient(RecipientType.TO, createAddress(subscriberEmail, null)); msg.setSubject(subject, Charsets.UTF_8.name()); msg.setText(text, Charsets.UTF_8.name()); sender.send(msg); } catch (MessagingException e) { log.error("error while sending mail", e); //$NON-NLS-1$ } } }
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException { // a brief validation if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) { throw new IllegalArgumentException(); }// w w w . j a v a2 s. co m Session session = getSession(); // Define a new mail message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (int i = 0; i < to.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } message.setSubject(mail.getSubject(), "utf-8"); // use a MimeMultipart as we need to handle the file attachments Multipart multipart = new MimeMultipart("alternative"); if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) { // add the message body to the mime message BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain" multipart.addBodyPart(textPart); } if (mail.getHtmlBody() != null) { BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8"); multipart.addBodyPart(pixPart); } // add any file attachments to the message addAtachments(mail.getAttachments(), multipart); // Put all message parts in the message message.setContent(multipart); // Send the message Transport.send(message); }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server/* www . j a v a 2 s. c om*/ * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static ErrorType sendMsg(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, final String port, final String security, final File fileAttachment) { String userName = uName; String password = pWord; if (StringUtils.isEmpty(toEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR"); return ErrorType.Error; } if (StringUtils.isEmpty(fromEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR"); return ErrorType.Error; } //if (isGmailEmail()) //{ // return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment); //} Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); boolean isSSL = security.equals("SSL"); String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable", "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback", "mail.imap.auth.plain.disable", }; Properties props = System.getProperties(); for (String key : keys) { props.remove(key); } props.put("mail.smtp.host", host); //$NON-NLS-1$ if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) { props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$ } else { props.remove("mail.smtp.port"); } if (StringUtils.isNotEmpty(security)) { if (security.equals("TLS")) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (isSSL) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.imap.auth.plain.disable", "true"); } } Session session = null; if (isSSL) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uName, pWord); } }); } else { session = Session.getInstance(props, null); } session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ log.debug("Port: " + port); //$NON-NLS-1$ log.debug("Security: " + security); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { try { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } catch (javax.mail.internet.AddressException ex) { UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr); return ErrorType.Error; } } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } final int TRIES = 1; // set the Date: header msg.setSentDate(new Date()); Exception exception = null; // send the message int cnt = 0; do { cnt++; SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { if (isSSL) { Transport.send(msg); } else { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); } fail = false; } catch (SendFailedException mex) { mex.printStackTrace(); exception = mex; } catch (MessagingException mex) { if (mex.getCause() instanceof UnknownHostException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host); } else if (mex.getCause() instanceof ConnectException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError( "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port); } else { mex.printStackTrace(); exception = mex; } } catch (Exception mex) { mex.printStackTrace(); exception = mex; } finally { if (t != null) { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } if (exception != null) { fail = true; instance.lastErrorMsg = exception.toString(); //wrong username or password, get new one if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName); userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) { //the user is done instance.lastErrorMsg = null; return ErrorType.Cancel; } userName = userAndPass.get(0); password = userAndPass.get(1); } } exception = null; } while (fail && cnt < TRIES); } catch (Exception mex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); mex.printStackTrace(); Exception ex = null; if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return ErrorType.Error; } if (fail) { return ErrorType.Error; } //else return ErrorType.OK; }
From source file:gov.nih.nci.caintegrator.application.mail.SendMail.java
public synchronized void sendMail(String mailTo, String mailCC, String mailBody, String subject) throws ValidationException { try {//from w ww .j ava2 s. co m if (mailTo != null && EmailValidator.getInstance().isValid(mailTo)) { //get system properties Properties props = System.getProperties(); String to = mailTo; // Set up mail server props.put("mail.smtp.host", MailConfig.getInstance(mailProperties).getHost()); //Get session Session session = Session.getDefaultInstance(props, null); //Define Message MimeMessage message = new MimeMessage(session); MailManager mailManager = new MailManager(mailProperties); message.setFrom(new InternetAddress(mailManager.formatFromAddress())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); if ((mailCC != null) && EmailValidator.getInstance().isValid(mailCC)) message.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCC)); message.setSubject(subject); message.setText(mailBody); //Send Message Transport.send(message); } else { throw new ValidationException("Invalid Email Address"); } } catch (Exception e) { logger.error("Send Mail error", e); } //catch }
From source file:org.ktunaxa.referral.server.command.test.TestEmailCommand.java
@Override public void execute(TestEmailRequest request, TestEmailResponse response) throws Exception { final String from = "rms@ktunaxa.org"; final String to = request.getTo(); if (null == to) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to"); }/*ww w. j a v a2s . co m*/ MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject("Test"); mimeMessage.setText("Testing RMS"); } }; mailSender.send(preparator); }
From source file:eu.scape_project.planning.application.Feedback.java
/** * Method responsible for sending feedback per mail. * /* w ww . j a va 2s.co m*/ * @param userEmail * email address of the user. * @param userComments * comments from the user * @param location * the location of the application where the error occurred * @param applicationName * the name of the application * @throws MailException * if the feedback could not be sent */ public void sendFeedback(String userEmail, String userComments, String location, String applicationName) 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(); builder.append("Date: ").append(dateFormat.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"); // Comments builder.append("Comments:\n"); builder.append(SEPARATOR_LINE); builder.append(userComments).append("\n"); builder.append(SEPARATOR_LINE).append("\n"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Feedback mail sent successfully to {}", config.getString("mail.feedback")); } catch (MessagingException e) { log.error("Error sending feedback mail to {}", config.getString("mail.feedback"), e); throw new MailException("Error sending feedback mail to " + config.getString("mail.feedback"), e); } }