Java Code Examples for javax.mail.internet.MimeMessage

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.

Source file: EmailSender.java

  28 
vote

/** 
 * Sends email.
 * @throws MessagingException message exception
 */
private void sendMail() throws MessagingException {
  final Properties props=new Properties();
  props.put("mail.smtp.host",MAIL_HOST);
  props.put("mail.smtp.auth","true");
  props.put("mail.smtp.starttls.enable","true");
  final Authenticator auth=new SMTPAuthenticator();
  final MimeMessage msg=new MimeMessage(Session.getDefaultInstance(props,auth));
  msg.setFrom(new InternetAddress(from));
  msg.setRecipient(RecipientType.TO,new InternetAddress(to));
  msg.setSubject(subject);
  msg.setText(message);
  Transport.send(msg);
}
 

Example 2

From project brix-cms, under directory /brix-demo/src/main/java/org/brixcms/demo/web/tile/feedback/.

Source file: FeedbackTilePanel.java

  25 
vote

private boolean sendMail(FeedbackMessage feedbackMessage){
  try {
    Session mailSession=Session.getDefaultInstance(WicketApplication.get().getProperties(),null);
    Transport transport=mailSession.getTransport();
    MimeMessage message=new MimeMessage(mailSession);
    message.setSubject("Feedback from " + feedbackMessage.email);
    message.setContent(feedbackMessage.message,"text/plain");
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(configuration.getEmail()));
    transport.connect();
    transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.close();
    return true;
  }
 catch (  Exception e) {
    error(getString("email.error",null,"unable to send feedback"));
    return false;
  }
}
 

Example 3

From project Cura, under directory /src/com/cura/security/.

Source file: GMailSender.java

  24 
vote

public synchronized void sendMail(String subject,String body,String sender,String recipients) throws Exception {
  try {
    MimeMessage message=new MimeMessage(session);
    DataHandler handler=new DataHandler(new ByteArrayDataSource(body.getBytes(),"text/plain"));
    message.setSender(new InternetAddress(sender));
    message.setSubject(subject);
    message.setDataHandler(handler);
    if (recipients.indexOf(',') > 0)     message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipients));
 else     message.setRecipient(Message.RecipientType.TO,new InternetAddress(recipients));
    Transport.send(message);
  }
 catch (  Exception e) {
  }
}
 

Example 4

From project eucalyptus, under directory /clc/modules/www/src/edu/ucsb/eucalyptus/admin/server/.

Source file: ServletUtils.java

  24 
vote

private static void send(String from,String to,String subject,String body) throws Exception {
  Properties properties=System.getProperties();
  Session session=Session.getDefaultInstance(properties);
  MimeMessage message=new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
  message.setSubject(subject);
  message.setText(body);
  Transport.send(message);
}
 

Example 5

From project james-hupa, under directory /server/src/test/java/org/apache/hupa/server/handler/.

Source file: GetMessageDetailsHandlerTest.java

  23 
vote

public void testMessageDetails_charsetIso() throws Exception {
  MimeMessage message=TestUtils.loadMessageFromFile(session,"3.msg");
  String from=message.getFrom()[0].toString();
  assertTrue(from.contains("\u00AE"));
  MessageDetails details=loadMessageDetails("3.msg");
  assertEquals(0,details.getMessageAttachments().size());
  assertTrue(details.getText().length() > 0);
}
 

Example 6

From project geronimo-javamail, under directory /geronimo-javamail_1.4/geronimo-javamail_1.4_provider/src/test/java/org/apache/geronimo/javamail/store/imap/.

Source file: IMAPStoreTest.java

  22 
vote

private void sendMessage(Session session,String msgFile) throws Exception {
  MimeMessage message;
  InputStream in=IMAPStoreTest.class.getResourceAsStream(msgFile);
  try {
    message=new MimeMessage(session,in);
  }
  finally {
    in.close();
  }
  Transport.send(message,new Address[]{new InternetAddress("[email protected]")});
}
 

Example 7

From project james, under directory /core/src/test/java/org/apache/james/core/.

Source file: MimeMessageTest.java

  22 
vote

protected MimeMessage getSimpleMessage() throws Exception {
  MimeMessage mmCreated=new MimeMessage(Session.getDefaultInstance(new Properties()));
  mmCreated.setSubject("test");
  mmCreated.setText("test body");
  mmCreated.saveChanges();
  return mmCreated;
}
 

Example 8

From project LABPipe, under directory /src/org/bultreebank/labpipe/utils/.

Source file: Emailer.java

  22 
vote

/** 
 * Send a single email.
 * @param aFromEmailAddr  from email address
 * @param aToEmailAddr    to email address
 * @param aSubject        email subject
 * @param aBody           email body
 */
public void sendEmail(String aFromEmailAddr,String aToEmailAddr,String aSubject,String aBody){
  Session session=Session.getDefaultInstance(OPTIONS,null);
  MimeMessage message=new MimeMessage(session);
  try {
    message.setFrom(new InternetAddress(OPTIONS.get("mail.from").toString()));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(aToEmailAddr));
    message.setSubject(aSubject);
    message.setText(aBody);
    Transport.send(message);
  }
 catch (  MessagingException ex) {
    log.log(Level.SEVERE,"Cannot send email. ",ex);
  }
}
 

Example 9

From project LGDEditTool, under directory /src/java/LGDEditTool/Email/.

Source file: Email.java

  22 
vote

/** 
 * Sends an email with the given values.
 * @param to receiver of the email
 * @param subject subject
 * @param text mail text
 * @param html send as html message
 * @return Returns <code>ture</code> after sending the mail.
 * @throws MessagingException 
 */
public boolean send(String to,String subject,String text,boolean html) throws MessagingException {
  Session session=Session.getDefaultInstance(this.properties,null);
  MimeMessage message=new MimeMessage(session);
  message.setFrom(new InternetAddress(this.properties.getProperty("mail.smtp.user")));
  message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
  message.setSubject(subject);
  if (html)   message.setContent(text,"text/html");
 else   message.setText(text);
  Transport transport=session.getTransport("smtp");
  transport.connect(this.properties.getProperty("mail.smtp.host"),this.properties.getProperty("mail.smtp.user"),this.properties.getProperty("mail.smtp.password"));
  transport.sendMessage(message,message.getAllRecipients());
  transport.close();
  return true;
}
 

Example 10

From project logback, under directory /logback-classic/src/test/java/ch/qos/logback/classic/net/.

Source file: SMTPAppender_GreenTest.java

  22 
vote

private MimeMultipart verify(String subject) throws MessagingException, IOException {
  MimeMessage[] mma=GREEN_MAIL_SERVER.getReceivedMessages();
  assertNotNull(mma);
  assertEquals(oldCount + 1,mma.length);
  MimeMessage mm=mma[oldCount];
  assertEquals(subject,mm.getSubject());
  return (MimeMultipart)mm.getContent();
}
 

Example 11

From project lorsource, under directory /src/main/java/ru/org/linux/user/.

Source file: LostPasswordController.java

  22 
vote

private void sendEmail(User user,String email,Timestamp resetDate) throws MessagingException {
  Properties props=new Properties();
  props.put("mail.smtp.host","localhost");
  Session mailSession=Session.getDefaultInstance(props,null);
  MimeMessage msg=new MimeMessage(mailSession);
  msg.setFrom(new InternetAddress("[email protected]"));
  String resetCode=getResetCode(configuration.getSecret(),user.getNick(),email,resetDate);
  msg.addRecipient(RecipientType.TO,new InternetAddress(email));
  msg.setSubject("Your password @linux.org.ru");
  msg.setSentDate(new Date());
  msg.setText("????????????!\n\n" + "??? ?????? ?????? ?????? ????????? ?? ?????? http://www.linux.org.ru/reset-password\n\n" + "??? ??? " + user.getNick() + ", ??? ?????????????: "+ resetCode+ "\n\n"+ "?????!");
  Transport.send(msg);
}
 

Example 12

From project mail, under directory /impl/src/main/java/org/jboss/seam/mail/util/.

Source file: MailUtility.java

  22 
vote

public static MimeMessage createMimeMessage(EmailMessage e,Session session){
  BaseMailMessage b=new BaseMailMessage(session,e.getCharset(),e.getRootContentType());
  if (!Strings.isNullOrBlank(e.getMessageId())) {
    b.setMessageID(e.getMessageId());
  }
  b.setFrom(e.getFromAddresses());
  b.addRecipients(RecipientType.TO,e.getToAddresses());
  b.addRecipients(RecipientType.CC,e.getCcAddresses());
  b.addRecipients(RecipientType.BCC,e.getBccAddresses());
  b.setReplyTo(e.getReplyToAddresses());
  b.addDeliveryRecieptAddresses(e.getDeliveryReceiptAddresses());
  b.addReadRecieptAddresses(e.getReadReceiptAddresses());
  b.setImportance(e.getImportance());
  b.addHeaders(e.getHeaders());
  if (e.getSubject() != null) {
    b.setSubject(e.getSubject());
  }
  if (e.getType() == EmailMessageType.STANDARD) {
    if (e.getHtmlBody() != null && e.getTextBody() != null) {
      b.setHTMLTextAlt(e.getHtmlBody(),e.getTextBody());
    }
 else     if (e.getTextBody() != null) {
      b.setText(e.getTextBody());
    }
 else     if (e.getHtmlBody() != null) {
      b.setHTML(e.getHtmlBody());
    }
    b.addAttachments(e.getAttachments());
  }
 else   if (e.getType() == EmailMessageType.INVITE_ICAL) {
    b.setHTMLNotRelated(e.getHtmlBody());
    b.addAttachments(e.getAttachments());
  }
 else {
    throw new SendFailedException("Unsupported Message Type: " + e.getType());
  }
  MimeMessage msg=b.getFinalizedMessage();
  return msg;
}
 

Example 13

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Mail/.

Source file: MailHandler.java

  21 
vote

private boolean sendMail(String subject,String message){
  MimeMessage msg=new MimeMessage(session);
  try {
    msg.setFrom(from);
    msg.setSubject(subject);
    msg.setText(message);
    msg.setRecipient(Message.RecipientType.TO,to);
    Transport.send(msg);
    return true;
  }
 catch (  Exception e) {
    ConsoleUtils.printException(e,Core.NAME,"Can't send mail!");
    return false;
  }
}
 

Example 14

From project accesointeligente, under directory /src/org/accesointeligente/server/.

Source file: Emailer.java

  21 
vote

public Boolean connectAndSend(){
  if (ApplicationProperties.getProperty("email.smtp") == null || ApplicationProperties.getProperty("email.user") == null || ApplicationProperties.getProperty("email.password") == null) {
    logger.error("No estan definidas las propiedades!");
    return false;
  }
  props.put("mail.smtp.host",ApplicationProperties.getProperty("email.smtp"));
  props.put("mail.smtp.port","465");
  props.put("mail.smtp.auth","true");
  props.put("mail.smtp.socketFactory.port","465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.socketFactory.fallback","false");
  if (getRecipient() == null || getSubject() == null || getBody() == null) {
    logger.error("No estan definidas las partes del correo");
    return false;
  }
  Session session=Session.getInstance(props,new Authenticator(){
    @Override protected PasswordAuthentication getPasswordAuthentication(){
      return new PasswordAuthentication(ApplicationProperties.getProperty("email.user"),ApplicationProperties.getProperty("email.password"));
    }
  }
);
  try {
    MimeMessage message=new MimeMessage(session);
    message.setFrom(new InternetAddress(ApplicationProperties.getProperty("email.user")));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(getRecipient()));
    message.setSubject(getSubject(),"UTF-8");
    message.setContent(getBody(),"text/html;charset=UTF-8");
    message.setSentDate(new Date());
    Transport.send(message);
    return true;
  }
 catch (  MessagingException ex) {
    logger.error("No se ha podido enviar el correo",ex);
  }
  return false;
}
 

Example 15

From project activiti, under directory /src/activiti-examples/org/activiti/examples/bpmn/mail/.

Source file: EmailSendTaskTest.java

  21 
vote

@Deployment @Test public void testSendEmail() throws Exception {
  String from="[email protected]";
  boolean male=true;
  String recipientName="John Doe";
  String recipient="[email protected]";
  Date now=new Date();
  String orderId="123456";
  Map<String,Object> vars=new HashMap<String,Object>();
  vars.put("sender",from);
  vars.put("recipient",recipient);
  vars.put("recipientName",recipientName);
  vars.put("male",male);
  vars.put("now",now);
  vars.put("orderId",orderId);
  RuntimeService runtimeService=activitiRule.getRuntimeService();
  runtimeService.startProcessInstanceByKey("sendMailExample",vars);
  List<WiserMessage> messages=wiser.getMessages();
  assertEquals(1,messages.size());
  WiserMessage message=messages.get(0);
  MimeMessage mimeMessage=message.getMimeMessage();
  assertEquals("Your order " + orderId + " has been shipped",mimeMessage.getHeader("Subject",null));
  assertEquals("\"" + from + "\" <"+ from.toString()+ ">",mimeMessage.getHeader("From",null));
  assertTrue(mimeMessage.getHeader("To",null).contains(recipient));
}
 

Example 16

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/util/.

Source file: Helpers.java

  21 
vote

public static void sendEmail(Set<String> recipients,String body,String subject) throws MessagingException {
  Properties props=new Properties();
  props.setProperty("mail.smtp.host","localhost");
  Session mailSession=Session.getDefaultInstance(props,null);
  MimeMessage message=new MimeMessage(mailSession);
  message.setSubject(subject);
  for (  String emailRecipient : recipients) {
    Address toAddress=new InternetAddress(emailRecipient);
    message.addRecipient(Message.RecipientType.TO,toAddress);
  }
  Address fromAddress=new InternetAddress("[email protected]");
  message.setFrom(fromAddress);
  message.setText(body);
  Transport.send(message);
  logger.info("Sent message '" + subject + "' to "+ recipients);
}
 

Example 17

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/company_server/.

Source file: MobileCompanyServer.java

  21 
vote

private void envoiPoliceEmail(String immatriculation,String emplacement,String modele){
  try {
    Properties property=System.getProperties();
    property.put("mail.smtp.host",MobileCompanyServer.prop.getProperty("MAIL_SMTP"));
    property.put("file.encoding","iso-8859-1");
    Session smtpSession=Session.getDefaultInstance(property,null);
    MimeMessage msg=new MimeMessage(smtpSession);
    msg.setFrom(new InternetAddress(MobileCompanyServer.prop.getProperty("EMAIL_SERVICE")));
    msg.setRecipient(Message.RecipientType.TO,new InternetAddress(MobileCompanyServer.prop.getProperty("EMAIL_POLICE")));
    msg.setSubject("Nouvelle constatation d'infraction");
    msg.setText("Nous avons constat?s un v?hicule qui a tent? une intrusion.\n" + "Le v?hicule est immatricul? " + immatriculation + " (mod?le : "+ modele+ ") et se trouve ? "+ emplacement);
    Transport.send(msg);
  }
 catch (  MessagingException ex) {
    Logger.getLogger(MobileServerThread.class.getName()).log(Level.SEVERE,null,ex);
  }
}
 

Example 18

From project coverity-plugin, under directory /src/main/java/jenkins/plugins/coverity/.

Source file: CoverityMailSender.java

  21 
vote

public boolean execute(CoverityBuildAction action,BuildListener listener) throws InterruptedException {
  try {
    MimeMessage mail=getMail(action,listener);
    if (mail != null) {
      Address[] allRecipients=mail.getAllRecipients();
      if (allRecipients != null) {
        StringBuilder buf=new StringBuilder("Sending e-mails to:");
        for (        Address a : allRecipients)         buf.append(' ').append(a);
        listener.getLogger().println(buf);
        Transport.send(mail);
      }
    }
  }
 catch (  MessagingException e) {
    e.printStackTrace(listener.error(e.getMessage()));
  }
catch (  CovRemoteServiceException_Exception e) {
    e.printStackTrace(listener.error(e.getMessage()));
  }
catch (  IOException e) {
    e.printStackTrace(listener.error(e.getMessage()));
  }
  return true;
}
 

Example 19

From project dawn-isencia, under directory /com.isencia.passerelle.actor/src/main/java/com/isencia/passerelle/actor/mail/.

Source file: MailMessageToMessageConverter.java

  21 
vote

public Object accept(Object message) throws Exception {
  if (logger.isTraceEnabled())   logger.trace("Accepting ~" + message.toString() + "~");
  ManagedMessage container=null;
  if (message != null) {
    container=MessageFactory.getInstance().createMessage();
    MimeMessage mailMessage=(MimeMessage)message;
    logger.debug("Creating new MessageContainer");
    Enumeration hdrEnum=mailMessage.getAllHeaders();
    while (hdrEnum.hasMoreElements()) {
      Header header=(Header)hdrEnum.nextElement();
      logger.debug("Name : " + header.getName() + ", Value : "+ header.getValue());
      container.addBodyHeader(header.getName(),header.getValue());
    }
    if (contentTypes == null && !attachInMessage)     return container;
    Object content=mailMessage.getContent();
    if (content instanceof String) {
      logger.debug("Content is String");
      if (contentTypes != null) {
        if (MessageHelper.filterContent(mailMessage,contentTypes)) {
          logger.debug("Content is Valid Content Type");
          container.setBodyContentPlainText((String)content);
        }
      }
    }
 else     if (content instanceof Multipart) {
      logger.debug("Content is Multipart");
      MultipartContentBuilder builder=new MultipartContentBuilder();
      Multipart mp=builder.build((Multipart)content,contentTypes,attachInMessage);
      if (mp != null) {
        logger.debug("Multipart added to BodyContent");
        ((MessageContainer)container).setBodyContent(mp);
      }
 else       logger.debug("No Multipart added to BodyContent");
    }
 else     if (content instanceof InputStream)     logger.debug("Content is Inputstream");
  }
  return container;
}
 

Example 20

From project elw, under directory /web/src/main/java/elw/webauth/.

Source file: ControllerAuth.java

  21 
vote

protected Message createMessage(final Session session,final HttpServletRequest req,final String emailAddress,final String smtpChallengeToken) throws MessagingException, UnsupportedEncodingException {
  final String mailBody=generateMailBody(req,emailAddress,smtpChallengeToken);
  final Message message=new MimeMessage(session);
  message.setSentDate(new Date());
  message.setFrom(new InternetAddress(serverConfig.getSmtpFrom()));
  message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(emailAddress));
  message.setSubject(serverConfig.getSmtpSubject());
  message.setText(mailBody);
  return message;
}
 

Example 21

From project gitblit, under directory /src/com/gitblit/.

Source file: MailExecutor.java

  21 
vote

/** 
 * Create a message.
 * @param toAddresses
 * @return a message
 */
public Message createMessage(List<String> toAddresses){
  MimeMessage message=new MimeMessage(session);
  try {
    String fromAddress=settings.getString(Keys.mail.fromAddress,null);
    if (StringUtils.isEmpty(fromAddress)) {
      fromAddress="[email protected]";
    }
    InternetAddress from=new InternetAddress(fromAddress,"Gitblit");
    message.setFrom(from);
    Set<String> uniques=new HashSet<String>();
    for (    String address : toAddresses) {
      uniques.add(address.toLowerCase());
    }
    Pattern validEmail=Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
    List<InternetAddress> tos=new ArrayList<InternetAddress>();
    for (    String address : uniques) {
      if (StringUtils.isEmpty(address)) {
        continue;
      }
      if (validEmail.matcher(address).find()) {
        try {
          tos.add(new InternetAddress(address));
        }
 catch (        Throwable t) {
        }
      }
    }
    message.setRecipients(Message.RecipientType.BCC,tos.toArray(new InternetAddress[tos.size()]));
    message.setSentDate(new Date());
  }
 catch (  Exception e) {
    logger.error("Failed to properly create message",e);
  }
  return message;
}
 

Example 22

From project GNDMS, under directory /infra/src/de/zib/gndms/infra/dspace/.

Source file: SliceReaper.java

  21 
vote

public void sendQuotaMail(final String recipient,final de.zib.gndms.infra.dspace.Slice slice,final String additionalMessage) throws MessagingException {
  final Properties props=new Properties();
  final Session session=Session.getDefaultInstance(props);
  final Message msg=new MimeMessage(session);
  props.put("mail.smtp.host",smtpServer);
  final InternetAddress addressFrom=new InternetAddress(from);
  final InternetAddress addressTo=new InternetAddress(recipient);
  msg.setFrom(addressFrom);
  msg.setRecipient(Message.RecipientType.TO,addressTo);
  msg.setSubject(subject);
  msg.setContent("Slice " + slice.getSubspace().getId() + "/"+ slice.getKind().getId()+ "/"+ slice.getId()+ " exceeds Quota.\n\n"+ "Owner: "+ slice.getOwner()+ "\n"+ "Size: "+ slice.getTotalStorageSize()+ " Bytes\n"+ "DiskUsage: "+ slice.getDiskUsage()+ " Bytes\n"+ "TerminationTime: "+ slice.getTerminationTime()+ additionalMessage,"text/plain");
  Transport.send(msg);
}
 

Example 23

From project gpslogger, under directory /GPSLogger/src/com/mendhak/gpslogger/senders/email/.

Source file: Mail.java

  21 
vote

boolean send() throws Exception {
  Properties props=_setProperties();
  if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
    Session session=Session.getInstance(props,this);
    MimeMessage msg=new MimeMessage(session);
    msg.setFrom(new InternetAddress(_from));
    InternetAddress[] addressTo=new InternetAddress[_to.length];
    for (int i=0; i < _to.length; i++) {
      addressTo[i]=new InternetAddress(_to[i]);
    }
    msg.setRecipients(MimeMessage.RecipientType.TO,addressTo);
    msg.setSubject(_subject);
    msg.setSentDate(new Date());
    BodyPart messageBodyPart=new MimeBodyPart();
    messageBodyPart.setText(_body);
    _multipart.addBodyPart(messageBodyPart);
    msg.setContent(_multipart);
    Transport.send(msg);
    return true;
  }
 else {
    return false;
  }
}
 

Example 24

From project jboss-as-quickstart, under directory /mail/src/main/java/org/jboss/as/quickstarts/mail/.

Source file: Email.java

  21 
vote

/** 
 * Method to send the email based upon values entered in the JSF view.  Exception should be handled in a production  usage but is not handled in this example.
 * @throws Exception
 */
public void send() throws Exception {
  Message message=new MimeMessage(mySession);
  message.setFrom(new InternetAddress(from));
  Address toAddress=new InternetAddress(to);
  message.addRecipient(Message.RecipientType.TO,toAddress);
  message.setSubject(subject);
  message.setContent(body,"text/plain");
  Transport.send(message);
}
 

Example 25

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/net/.

Source file: MailSender.java

  21 
vote

/** 
 * Creates a simple MIME message with some basic headers.
 * @param from the 'from' mail address.
 * @param to the 'to' mail address(es).
 * @param cc the 'cc' mail address(es).
 * @param subject the mail subject.
 * @param session the mail session.
 * @return a new MIME message.
 * @throws ConnectionException if error occurred in constructing the mailmessage.
 */
public MimeMessage createMessage(String from,String to,String cc,String subject,Session session) throws ConnectionException {
  MimeMessage msg=createMessage(session);
  try {
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to,false));
    if (cc != null) {
      msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc,false));
    }
    if (subject != null) {
      msg.setSubject(subject);
    }
    return msg;
  }
 catch (  Exception e) {
    throw new ConnectionException("Error in constructing mail message",e);
  }
}
 

Example 26

From project jspwiki, under directory /src/org/apache/wiki/util/.

Source file: MailUtil.java

  21 
vote

/** 
 * <p>Sends an e-mail to a specified receiver using a JavaMail Session supplied by a JNDI mail session factory (preferred) or a locally initialized session based on properties in <code>jspwiki.properties</code>. See the top-level JavaDoc for this class for a description of required properties and their default values.</p> <p>The e-mail address used for the <code>to</code> parameter must be in RFC822 format, as described in the JavaDoc for  {@link javax.mail.internet.InternetAddress}and more fully at <a href="http://www.freesoft.org/CIE/RFC/822/index.htm">http://www.freesoft.org/CIE/RFC/822/index.htm</a>. In other words, e-mail addresses should look like this:</p> <blockquote><code>Snoop Dog &lt;[email protected]&gt;<br/> [email protected]</code></blockquote> <p>Note that the first form allows a "friendly" user name to be supplied in addition to the actual e-mail address.</p>
 * @param engine the WikiEngine for the current wiki
 * @param to the receiver
 * @param subject the subject line of the message
 * @param content the contents of the mail message, as plain text
 * @throws AddressException If the address is invalid
 * @throws MessagingException If the message cannot be sent.
 */
public static void sendMessage(WikiEngine engine,String to,String subject,String content) throws AddressException, MessagingException {
  Properties props=engine.getWikiProperties();
  Session session=getMailSession(engine);
  getSenderEmailAddress(session,props);
  try {
    MimeMessage msg=new MimeMessage(session);
    msg.setFrom(new InternetAddress(c_fromAddress));
    msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to,false));
    msg.setSubject(subject);
    msg.setText(content,"UTF-8");
    msg.setSentDate(new Date());
    Transport.send(msg);
    if (log.isInfoEnabled()) {
      log.info("Sent e-mail to=" + to + ", subject=\""+ subject+ "\", used "+ (c_useJndi ? "JNDI" : "standalone")+ " mail session.");
    }
  }
 catch (  MessagingException e) {
    log.error(e);
    throw e;
  }
}
 

Example 27

From project kernel_1, under directory /exo.kernel.component.common/src/test/java/org/exoplatform/services/mail/test/.

Source file: TestMailService.java

  21 
vote

public void testSendMimeMessage() throws Exception {
  MimeMessage message=new MimeMessage(service.getMailSession());
  message.setFrom(new InternetAddress(generateRandomEmailSender()));
  message.setRecipients(javax.mail.Message.RecipientType.TO,generateRandomEmailRecipient());
  message.setSubject(MAIL_SUBJECT);
  message.setContent(MAIL_CONTENTS,TEXT_PLAIN);
  Flags flags=new Flags();
  flags.add(Flags.Flag.RECENT);
  message.setFlags(flags,true);
  assertEquals("SMTP server should be now empty",0,mailServer.getMessages().size());
  assertFalse(isEmailMessageSent(MAIL_SUBJECT));
  service.sendMessage(message);
  Thread.sleep(ONE_SECOND);
  assertEquals("SMTP server should have one message",1,mailServer.getMessages().size());
  assertTrue(isEmailMessageSent(MAIL_SUBJECT));
}
 

Example 28

From project lor-jamwiki, under directory /jamwiki-web/src/main/java/org/jamwiki/mail/.

Source file: WikiMail.java

  21 
vote

/** 
 * Send mail via SMTP. MessagingExceptions are silently dropped.
 * @param from the RFC 821 "MAIL FROM" parameter
 * @param to the RFC 821 "RCPT TO" parameter
 * @param subject the RFC 822 "Subject" field
 * @param body the RFC 822 "Body" field
 */
public void sendMail(String from,String to,String subject,String body){
  try {
    MimeMessage message=new MimeMessage(session);
    InternetAddress internetAddress=new InternetAddress(from);
    message.setFrom(internetAddress);
    message.setReplyTo(new InternetAddress[]{internetAddress});
    message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
    message.setSubject(subject);
    message.setText(body);
    message.setSentDate(new Date());
    message.saveChanges();
    Transport.send(message);
  }
 catch (  MessagingException e) {
    logger.warn("Mail error",e);
  }
}
 

Example 29

From project mateo, under directory /src/main/java/mx/edu/um/mateo/general/web/.

Source file: BaseController.java

  21 
vote

protected void enviaCorreo(String tipo,List<?> lista,HttpServletRequest request,String nombre,String tipoReporte,Long id) throws ReporteException {
  try {
    log.debug("Enviando correo {}",tipo);
    byte[] archivo=null;
    String tipoContenido=null;
switch (tipo) {
case "PDF":
      archivo=generaPdf(lista,nombre,tipoReporte,id);
    tipoContenido="application/pdf";
  break;
case "CSV":
archivo=generaCsv(lista,nombre,tipoReporte,id);
tipoContenido="text/csv";
break;
case "XLS":
archivo=generaXls(lista,nombre,tipoReporte,id);
tipoContenido="application/vnd.ms-excel";
}
MimeMessage message=mailSender.createMimeMessage();
MimeMessageHelper helper=new MimeMessageHelper(message,true);
helper.setTo(ambiente.obtieneUsuario().getCorreo());
String titulo=messageSource.getMessage(nombre + ".reporte.label",null,request.getLocale());
helper.setSubject(messageSource.getMessage("envia.correo.titulo.message",new String[]{titulo},request.getLocale()));
helper.setText(messageSource.getMessage("envia.correo.contenido.message",new String[]{titulo},request.getLocale()),true);
helper.addAttachment(titulo + "." + tipo,new ByteArrayDataSource(archivo,tipoContenido));
mailSender.send(message);
}
 catch (JRException|MessagingException e) {
throw new ReporteException("No se pudo generar el reporte",e);
}
}
 

Example 30

From project meetupnow, under directory /src/meetupnow/.

Source file: MailHandlerServlet.java

  21 
vote

public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
  Properties props=new Properties();
  Session session=Session.getDefaultInstance(props,null);
  PersistenceManager pm=PMF.get().getPersistenceManager();
  try {
    MimeMessage message=new MimeMessage(session,req.getInputStream());
    Suggestion sug=new Suggestion();
    String output="";
    Object content=message.getContent();
    if (content instanceof String) {
      output=((String)message.getContent());
    }
 else     if (content instanceof Multipart) {
      Multipart mp=(Multipart)content;
      int parts=mp.getCount();
      BodyPart bodyPart=mp.getBodyPart(0);
      Object o2=bodyPart.getContent();
      output=output.concat((String)o2);
    }
    sug.setTo(message.getAllRecipients()[0].toString());
    sug.setContent(output);
    sug.setSubject(message.getSubject());
    sug.setAddress(message.getFrom()[0].toString());
    try {
      pm.makePersistent(sug);
    }
  finally {
      pm.close();
    }
  }
 catch (  Exception e) {
    System.out.println(e);
  }
}
 

Example 31

From project message-wrapper, under directory /src/main/java/jp/co/worksap/message/wrapper/.

Source file: MessageWrapper.java

  21 
vote

public MessageWrapper(@Nullable Session session,@Nonnull InputStream is){
  checkNotNull(is);
  try {
    this.instance=new MimeMessage(session,is);
  }
 catch (  MessagingException e) {
    throw new RuntimeException("Failed to crate MessageWrapper",e);
  }
}
 

Example 32

From project micromailer, under directory /src/main/java/org/sonatype/micromailer/imp/.

Source file: DefaultMailSender.java

  21 
vote

public void sendMail(EmailerConfiguration configuration,MailRequest request,MailType mailType) throws MailCompositionAttachmentException, MailCompositionMessagingException {
  try {
    Session session=configuration.getSession();
    MimeMessage message=request.getMimeMessage();
    message.saveChanges();
    Transport t=session.getTransport();
    try {
      t.connect();
      t.sendMessage(message,message.getAllRecipients());
    }
  finally {
      t.close();
    }
  }
 catch (  MessagingException ex) {
    throw new MailCompositionMessagingException("MessagingException occured!",ex);
  }
}
 

Example 33

From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/util/.

Source file: MailUtil.java

  20 
vote

public static void sendEmail(String to,String from,String subject,String body,String host,String username,String password,boolean secure){
  Properties mailProps=new Properties();
  mailProps.setProperty("mail.transport.protocol","smtp");
  mailProps.setProperty("mail.smtp.host",host);
  mailProps.setProperty("mail.smtp.submitter",username);
  if (System.getProperty("os.name").toLowerCase().contains("mac")) {
    mailProps.setProperty("mail.smtp.starttls.enable","true");
    mailProps.setProperty("mail.smtp.ssl.trust","smtpserver");
  }
  if (secure) {
    mailProps.setProperty("mail.smtp.socketFactory.port","465");
    mailProps.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  }
  Authenticator mailAuth=null;
  if (username != null) {
    mailAuth=new MailAuthenticator(username,password);
    mailProps.setProperty("mail.smtp.auth","true");
  }
  Session session=Session.getDefaultInstance(mailProps,mailAuth);
  Message message=new MimeMessage(session);
  try {
    message.setFrom(new InternetAddress(from));
    message.setSubject(subject);
    message.setHeader("To",to);
    message.setContent(body,"text/html");
    Transport.send(message,new InternetAddress[]{new InternetAddress(to)});
  }
 catch (  MessagingException e) {
    Manager.getLogger(MailUtil.class.getName()).error("Error sending email",e);
  }
}
 

Example 34

From project azkaban, under directory /azkaban/src/java/azkaban/app/.

Source file: Mailman.java

  20 
vote

public void sendEmail(String fromAddress,List<String> toAddress,String subject,String body) throws MessagingException {
  Properties props=new Properties();
  props.setProperty("mail.transport.protocol","smtp");
  props.put("mail.host",_mailHost);
  props.put("mail.user",_mailUser);
  props.put("mail.password",_mailPassword);
  Session session=Session.getDefaultInstance(props);
  Message message=new MimeMessage(session);
  InternetAddress from=new InternetAddress(fromAddress == null ? "[email protected]" : fromAddress,false);
  message.setFrom(from);
  for (  String toAddr : toAddress)   message.addRecipient(Message.RecipientType.TO,new InternetAddress(toAddr,false));
  message.setSubject(subject);
  message.setText(body);
  message.setSentDate(new Date());
  Transport.send(message);
}
 

Example 35

From project capedwarf-green, under directory /server-jee/src/main/java/org/jboss/capedwarf/server/jee/mail/.

Source file: BasicMailManager.java

  20 
vote

public void sendEmail(String sender,String subject,String textBody,String... tos){
  if (session == null)   return;
  try {
    Address[] addresses=new Address[tos.length];
    for (int i=0; i < tos.length; i++)     addresses[i]=new InternetAddress(tos[i]);
    Message msg=new MimeMessage(session);
    msg.setFrom(new InternetAddress(sender));
    msg.addRecipients(Message.RecipientType.TO,addresses);
    msg.setSubject(subject);
    msg.setText(textBody);
    Transport.send(msg);
  }
 catch (  Exception e) {
    log.warning("Failed to send email: " + e);
  }
}
 

Example 36

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/net/.

Source file: SMTPAppender.java

  20 
vote

/** 
 * Activate the specified options, such as the smtp host, the recipient, from, etc. 
 */
public void activateOptions(){
  Session session=createSession();
  msg=new MimeMessage(session);
  try {
    addressMessage(msg);
    if (subject != null) {
      try {
        msg.setSubject(MimeUtility.encodeText(subject,"UTF-8",null));
      }
 catch (      UnsupportedEncodingException ex) {
        LogLog.error("Unable to encode SMTP subject",ex);
      }
    }
  }
 catch (  MessagingException e) {
    LogLog.error("Could not activate SMTPAppender options.",e);
  }
  if (evaluator instanceof OptionHandler) {
    ((OptionHandler)evaluator).activateOptions();
  }
}
 

Example 37

From project figgo, under directory /src/main/java/br/octahedron/figgo/util/.

Source file: Mailer.java

  20 
vote

public static void send(String name,String from,String subject,String message){
  Properties props=new Properties();
  Session session=Session.getDefaultInstance(props,null);
  Message msg=new MimeMessage(session);
  try {
    msg.setFrom(new InternetAddress(from,name));
    msg.addRecipient(Message.RecipientType.TO,new InternetAddress(CotopaxiProperty.getProperty("MAIL_TO"),"Figgo"));
    msg.setSubject(subject);
    msg.setText(message);
    Transport.send(msg);
  }
 catch (  Exception e) {
    log.warning("Cannot send mail from %s (%s) with '%s' as subject and '%s' as the message",name,from,subject,message);
  }
}
 

Example 38

From project google-app-engine-jappstart, under directory /src/main/java/com/jappstart/service/mail/.

Source file: MailService.java

  20 
vote

/** 
 * Sends the activation e-mail to the given user.
 * @param user the user
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user,final String locale) throws MessagingException {
  final Properties props=new Properties();
  final Session session=Session.getDefaultInstance(props,null);
  final Message message=new MimeMessage(session);
  final Multipart multipart=new MimeMultipart();
  final MimeBodyPart htmlPart=new MimeBodyPart();
  final MimeBodyPart textPart=new MimeBodyPart();
  message.setFrom(new InternetAddress(getFromAddress()));
  message.addRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
  message.setSubject(messageSource.getMessage("mail.subject",null,new Locale(locale)));
  textPart.setContent(messageSource.getMessage("mail.body.txt",new Object[]{getHostname(),user.getActivationKey()},new Locale(locale)),"text/plain");
  htmlPart.setContent(messageSource.getMessage("mail.body.html",new Object[]{getHostname(),user.getActivationKey()},new Locale(locale)),"text/html");
  multipart.addBodyPart(textPart);
  multipart.addBodyPart(htmlPart);
  message.setContent(multipart);
  Transport.send(message);
}
 

Example 39

From project guj.com.br, under directory /src/net/jforum/util/mail/.

Source file: Spammer.java

  20 
vote

/** 
 * Prepares the mail message for sending.
 * @param subject the subject of the email
 * @param messageFile the path to the mail message template
 * @throws MailException
 */
protected void prepareMessage(String subject,String messageFile) throws MailException {
  if (this.messageId != null) {
    this.message=new IdentifiableMimeMessage(session);
    ((IdentifiableMimeMessage)this.message).setMessageId(this.messageId);
  }
 else {
    this.message=new MimeMessage(session);
  }
  this.templateParams.put("forumName",SystemGlobals.getValue(ConfigKeys.FORUM_NAME));
  try {
    this.message.setSentDate(new Date());
    this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
    this.message.setSubject(subject,SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
    if (this.inReplyTo != null) {
      this.message.addHeader("In-Reply-To",this.inReplyTo);
    }
    this.createTemplate(messageFile);
    this.needCustomization=this.isCustomizationNeeded();
    if (!this.needCustomization) {
      String text=this.processTemplate();
      this.defineMessageText(text);
    }
  }
 catch (  Exception e) {
    throw new MailException(e);
  }
}
 

Example 40

From project gxa, under directory /atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/helper/.

Source file: FeedbackRequestHandler.java

  20 
vote

public void handleRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  boolean success=false;
  StringBuilder sb=new StringBuilder();
  try {
    boolean debug=false;
    Properties props=new Properties();
    props.put("mail.smtp.host",atlasProperties.getFeedbackSmtpHost());
    Session smtpSession=Session.getDefaultInstance(props,null);
    smtpSession.setDebug(debug);
    Message msg=new MimeMessage(smtpSession);
    msg.setRecipients(Message.RecipientType.TO,new InternetAddress[]{new InternetAddress(atlasProperties.getFeedbackToAddress(),true)});
    String email=request.getParameter("email");
    if (Strings.isNullOrEmpty(email)) {
      email=atlasProperties.getFeedbackFromAddress();
    }
    InternetAddress addressFrom=new InternetAddress(email,true);
    msg.setFrom(addressFrom);
    msg.setReplyTo(new InternetAddress[]{addressFrom});
    msg.setSubject(atlasProperties.getFeedbackSubject());
    sb.append("URL: ").append(request.getParameter("url")).append("\n");
    sb.append("What were you trying to do:\n\t").append(request.getParameter("context")).append("\n");
    sb.append("What went wrong:\n\t").append(request.getParameter("error")).append("\n");
    sb.append("What could be done better:\n\t").append(request.getParameter("dobetter")).append("\n");
    msg.setContent(sb.toString(),"text/plain");
    Transport.send(msg);
    response.getWriter().write("SEND OK");
    success=true;
  }
 catch (  AddressException e) {
    log.error(e.getMessage() + " while sending:\n " + sb.toString()+ "\n",e);
  }
catch (  MessagingException e) {
    log.error(e.getMessage() + " while sending:\n " + sb.toString()+ "\n",e);
  }
 finally {
    if (!success)     response.getWriter().write("SEND FAIL");
  }
}
 

Example 41

From project hank, under directory /src/java/com/rapleaf/hank/monitor/notifier/email/.

Source file: EmailSummaryNotifier.java

  20 
vote

private void sendEmails(Set<String> emailTargets,String body) throws IOException, InterruptedException {
  Session session=Session.getDefaultInstance(emailSessionProperties);
  Message message=new MimeMessage(session);
  try {
    message.setSubject("Hank monitor: " + name);
    message.setFrom(new InternetAddress(emailFrom));
    for (    String emailTarget : emailTargets) {
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTarget));
    }
    message.setContent(body,"text/html");
    Transport.send(message);
  }
 catch (  MessagingException e) {
    throw new RuntimeException("Failed to send notification email.",e);
  }
}
 

Example 42

From project Hesperid, under directory /server/src/main/java/ch/astina/hesperid/web/services/mail/impl/.

Source file: MailerServiceImpl.java

  20 
vote

/** 
 * Prepares a Message object based on the given MailMessage object
 */
private Message prepareMessage(Session session,MailMessage mailMessage) throws IncompleteMailException, MessagingException {
  logger.info("Creating email \"{}\" for {}",mailMessage.getSubject(),mailMessage.getToRecipientsArray());
  Address sender=mailMessage.getSender();
  String subject=mailMessage.getSubject();
  if (sender == null) {
    throw new IncompleteMailException("No sender given");
  }
  Message message=new MimeMessage(session);
  message.setFrom(sender);
  message.setRecipients(Message.RecipientType.TO,checkRecipients(mailMessage.getToRecipientsArray()));
  message.setRecipients(Message.RecipientType.CC,checkRecipients(mailMessage.getCcRecipientsArray()));
  message.setRecipients(Message.RecipientType.BCC,checkRecipients(mailMessage.getBccRecipientsArray()));
  message.setSubject(subject);
  message.setSentDate(new Date());
  return message;
}
 

Example 43

From project huiswerk, under directory /print/zxing-1.6/zxingorg/src/com/google/zxing/web/.

Source file: DecodeEmailTask.java

  20 
vote

private void processMessagePart(Session session,Message message,MimeBodyPart part) throws MessagingException, IOException {
  String contentType=part.getContentType();
  if (contentType.startsWith("image/")) {
    BufferedImage image=ImageIO.read(part.getInputStream());
    if (image != null) {
      Reader reader=new MultiFormatReader();
      Result result=null;
      try {
        LuminanceSource source=new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap=new BinaryBitmap(new HybridBinarizer(source));
        result=reader.decode(bitmap,DecodeServlet.HINTS);
      }
 catch (      ReaderException re) {
        log.info("Decoding FAILED");
      }
      Message reply=new MimeMessage(session);
      Address sender=message.getFrom()[0];
      reply.setRecipient(Message.RecipientType.TO,sender);
      reply.setFrom(fromAddress);
      if (result == null) {
        reply.setSubject("Decode failed");
        reply.setContent("Sorry, we could not decode that image.","text/plain");
      }
 else {
        String text=result.getText();
        reply.setSubject("Decode succeeded");
        reply.setContent(text,"text/plain");
      }
      log.info("Sending reply");
      Transport.send(reply);
    }
  }
}
 

Example 44

From project java-maven-tests, under directory /src/jappstart-gwitter/src/main/java/com/jappstart/service/mail/.

Source file: MailService.java

  20 
vote

/** 
 * Sends the activation e-mail to the given user.
 * @param user the user
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user,final String locale) throws MessagingException {
  final Properties props=new Properties();
  final Session session=Session.getDefaultInstance(props,null);
  final Message message=new MimeMessage(session);
  final Multipart multipart=new MimeMultipart();
  final MimeBodyPart htmlPart=new MimeBodyPart();
  final MimeBodyPart textPart=new MimeBodyPart();
  message.setFrom(new InternetAddress(getFromAddress()));
  message.addRecipient(Message.RecipientType.TO,new InternetAddress(user.getEmail()));
  message.setSubject(messageSource.getMessage("mail.subject",null,new Locale(locale)));
  textPart.setContent(messageSource.getMessage("mail.body.txt",new Object[]{getHostname(),user.getActivationKey()},new Locale(locale)),"text/plain");
  htmlPart.setContent(messageSource.getMessage("mail.body.html",new Object[]{getHostname(),user.getActivationKey()},new Locale(locale)),"text/html");
  multipart.addBodyPart(textPart);
  multipart.addBodyPart(htmlPart);
  message.setContent(multipart);
  Transport.send(message);
}
 

Example 45

From project jforum2, under directory /src/net/jforum/util/mail/.

Source file: Spammer.java

  20 
vote

/** 
 * Prepares the mail message for sending.
 * @param subject the subject of the email
 * @param messageFile the path to the mail message template
 * @throws MailException
 */
protected void prepareMessage(String subject,String messageFile) throws MailException {
  if (this.messageId != null) {
    this.message=new IdentifiableMimeMessage(session);
    ((IdentifiableMimeMessage)this.message).setMessageId(this.messageId);
  }
 else {
    this.message=new MimeMessage(session);
  }
  this.templateParams.put("forumName",SystemGlobals.getValue(ConfigKeys.FORUM_NAME));
  try {
    this.message.setSentDate(new Date());
    this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
    this.message.setSubject(subject,SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
    if (this.inReplyTo != null) {
      this.message.addHeader("In-Reply-To",this.inReplyTo);
    }
    this.createTemplate(messageFile);
    this.needCustomization=this.isCustomizationNeeded();
    if (!this.needCustomization) {
      String text=this.processTemplate();
      this.defineMessageText(text);
    }
  }
 catch (  Exception e) {
    throw new MailException(e);
  }
}
 

Example 46

From project jibu, under directory /plugins/jibu-mail/src/main/java/org/gaixie/jibu/mail/.

Source file: JavaMailSender.java

  20 
vote

/** 
 * ??? javax.mail ?????? <p>
 * @param from ???????????
 * @param recipients ????????????????????????????   
 * @param subj ???????
 * @param text ???????
 */
public void sendEmail(String from,String recipients,String subj,String text){
  Properties props=new Properties();
  Session session=Session.getDefaultInstance(props,null);
  try {
    InternetAddress[] address=InternetAddress.parse(recipients);
    Message msg=new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.addRecipients(Message.RecipientType.TO,address);
    msg.setSubject(subj);
    msg.setText(text);
    Transport.send(msg);
  }
 catch (  AddressException e) {
    System.out.println(e.getMessage());
  }
catch (  MessagingException e) {
    System.out.println(e.getMessage());
  }
}
 

Example 47

From project log4j, under directory /src/main/java/org/apache/log4j/net/.

Source file: SMTPAppender.java

  20 
vote

/** 
 * Activate the specified options, such as the smtp host, the recipient, from, etc. 
 */
public void activateOptions(){
  Session session=createSession();
  msg=new MimeMessage(session);
  try {
    addressMessage(msg);
    if (subject != null) {
      try {
        msg.setSubject(MimeUtility.encodeText(subject,"UTF-8",null));
      }
 catch (      UnsupportedEncodingException ex) {
        LogLog.error("Unable to encode SMTP subject",ex);
      }
    }
  }
 catch (  MessagingException e) {
    LogLog.error("Could not activate SMTPAppender options.",e);
  }
  if (evaluator instanceof OptionHandler) {
    ((OptionHandler)evaluator).activateOptions();
  }
}
 

Example 48

From project log4jna, under directory /thirdparty/log4j/src/main/java/org/apache/log4j/net/.

Source file: SMTPAppender.java

  20 
vote

/** 
 * Activate the specified options, such as the smtp host, the recipient, from, etc. 
 */
public void activateOptions(){
  Session session=createSession();
  msg=new MimeMessage(session);
  try {
    addressMessage(msg);
    if (subject != null) {
      try {
        msg.setSubject(MimeUtility.encodeText(subject,"UTF-8",null));
      }
 catch (      UnsupportedEncodingException ex) {
        LogLog.error("Unable to encode SMTP subject",ex);
      }
    }
  }
 catch (  MessagingException e) {
    LogLog.error("Could not activate SMTPAppender options.",e);
  }
  if (evaluator instanceof OptionHandler) {
    ((OptionHandler)evaluator).activateOptions();
  }
}
 

Example 49

From project mail_1, under directory /impl/src/main/java/br/gov/frameworkdemoiselle/mail/internal/.

Source file: Dispatcher.java

  20 
vote

private MimeMessage createMimeMessage(){
  mimeMessage=new MimeMessage(session);
  try {
    mimeMessage.setContent(multipart);
    setFrom();
    setTo();
    setCc();
    setBcc();
    setReplyTo();
    setReadReceipt();
    setDeliveryReceipt();
    setImportance();
    setAttachments();
    mimeMessage.setSubject(message.getSubject(),charset);
    setContent();
  }
 catch (  Exception e) {
    throw new MailException("Error preparing e-mail message",e);
  }
  return mimeMessage;
}
 

Example 50

From project ajah, under directory /ajah-rfcmail/src/main/java/com/ajah/rfcmail/fetch/.

Source file: IMAPMailFetcher.java

  19 
vote

private void processFolder(final IMAPFolder folder) throws MessagingException, IOException {
  log.fine("Processing folder " + folder.getFullName());
  final long start=System.currentTimeMillis();
  if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
    folder.open(Folder.READ_ONLY);
    final Message[] messages=folder.getMessages();
    log.fine(messages.length + " messages");
    final FetchProfile fp=new FetchProfile();
    fp.add("Message-Id");
    folder.fetch(messages,fp);
    long messageCount=0;
    for (    final Message message : messages) {
      messageCount++;
      try {
        for (        final MessageHandler messageHandler : getMessageHandlers()) {
          log.finest(messageHandler.getClass().getSimpleName() + " handling " + ((MimeMessage)message).getMessageID());
          messageHandler.handle(new AjahMimeMessage(message.getInputStream()));
          return;
        }
      }
 catch (      final MessagingException e) {
        log.log(Level.SEVERE,e.getMessage(),e);
      }
    }
    log.finest(messageCount + " messages");
  }
  final long end=System.currentTimeMillis();
  log.finest("Processed " + folder.getFullName() + " in "+ (end - start)+ "ms");
  if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
    final Folder[] children=folder.list();
    if (children != null) {
      for (      final Folder child : children) {
        processFolder((IMAPFolder)child);
      }
    }
  }
}
 

Example 51

From project Carolina-Digital-Repository, under directory /persistence/src/test/java/edu/unc/lib/dl/util/.

Source file: MockJavaMailSender.java

  19 
vote

private void logit(MimeMessage msg){
  log.debug("Dumping message content to standard out.");
  try {
    msg.writeTo(System.out);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  MessagingException e) {
    e.printStackTrace();
  }
}
 

Example 52

From project milton, under directory /milton/examples/caldav-non-spring-netbeans/src/java/com/ettrema/http/caldav/demo/.

Source file: TMailFolder.java

  19 
vote

public void storeMail(MimeMessage mm){
  StandardMessageFactoryImpl factoryImpl=new StandardMessageFactoryImpl();
  StandardMessageImpl sm=new StandardMessageImpl();
  factoryImpl.toStandardMessage(mm,sm);
  TMessageResource mr=new TMessageResource(this,"msg-" + nextMsgId++,sm);
  System.out.println("stored message in: " + mr.getName());
}
 

Example 53

From project milton2, under directory /examples/caldav-non-spring-netbeans/src/java/com/ettrema/http/caldav/demo/.

Source file: TMailFolder.java

  19 
vote

public void storeMail(MimeMessage mm){
  StandardMessageFactoryImpl factoryImpl=new StandardMessageFactoryImpl();
  StandardMessageImpl sm=new StandardMessageImpl();
  factoryImpl.toStandardMessage(mm,sm);
  TMessageResource mr=new TMessageResource(this,"msg-" + nextMsgId++,sm);
  System.out.println("stored message in: " + mr.getName());
}