Java Code Examples for javax.mail.Message

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 capedwarf-blue, under directory /mail/src/test/java/org/jboss/test/capedwarf/mail/test/.

Source file: MessageConverterTestCase.java

  22 
vote

@Test public void senderIsSetCorrectly() throws Exception {
  gaeMessage.setSender("[email protected]");
  Message convertedMessage=convertMessage();
  Address[] fromAddresses=convertedMessage.getFrom();
  assertThat(fromAddresses.length,is(1));
  Address fromAddress=fromAddresses[0];
  assertEquals(new InternetAddress("[email protected]"),fromAddress);
}
 

Example 2

From project echo2, under directory /src/exampleapp/email/src/java/echo2example/email/faux/.

Source file: FauxFolder.java

  22 
vote

public int compare(Object a,Object b){
  try {
    Message message1=(Message)a;
    Message message2=(Message)b;
    int dateDelta=message1.getSentDate().compareTo(message2.getSentDate());
    if (dateDelta != 0) {
      return dateDelta;
    }
    return message1.toString().compareTo(message2.toString());
  }
 catch (  MessagingException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 3

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

Source file: ControllerAuth.java

  22 
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 4

From project geronimo-javamail, under directory /geronimo-javamail_1.4/geronimo-javamail_1.4_provider/src/main/java/org/apache/geronimo/javamail/handlers/.

Source file: RFC822MessageHandler.java

  22 
vote

/** 
 * Write an RFC 822 message object out to an output stream.
 * @param obj      The source message object.
 * @param mimeType The target mimetype
 * @param os       The target output stream.
 * @exception IOException
 */
public void writeTo(Object obj,String mimeType,OutputStream os) throws IOException {
  if (obj instanceof Message) {
    Message message=(Message)obj;
    try {
      message.writeTo(os);
    }
 catch (    MessagingException e) {
      throw (IOException)new IOException(e.getMessage()).initCause(e);
    }
  }
}
 

Example 5

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

Source file: GitBlit.java

  22 
vote

/** 
 * Notify the administrators by email.
 * @param subject
 * @param message
 */
public void sendMailToAdministrators(String subject,String message){
  try {
    Message mail=mailExecutor.createMessageForAdministrators();
    if (mail != null) {
      mail.setSubject(subject);
      mail.setText(message);
      mailExecutor.queue(mail);
    }
  }
 catch (  MessagingException e) {
    logger.error("Messaging error",e);
  }
}
 

Example 6

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

Source file: SliceReaper.java

  22 
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 7

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

Source file: MailerServiceImpl.java

  22 
vote

@Override public void sendTextMail(TextMailMessage mailMessage) throws MessagingException {
  Session session=Session.getInstance(mailProperties,authenticator);
  try {
    Message message=prepareMessage(session,mailMessage);
    completeTextMessage(message,mailMessage);
    Transport.send(message);
  }
 catch (  Exception ex) {
    logger.error("The text message could not be sent",ex);
    throw new MessagingException(ex.getCause() + " > " + ex.getMessage(),ex);
  }
}
 

Example 8

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

Source file: AbtractSendMessageHandlerTest.java

  22 
vote

public void testExecute() throws Exception {
  IMAPStore store=storeCache.get(testUser);
  MockIMAPFolder sentbox=(MockIMAPFolder)store.getFolder(MockIMAPStore.MOCK_SENT_FOLDER);
  SMTPMessage smtpmsg=TestUtils.createMockSMTPMessage(SessionUtils.getSessionRegistry(logger,httpSession),2);
  SendMessage action=new SendMessage(smtpmsg);
  assertTrue(sentbox.getMessages().length == 0);
  sendMessageHandler.execute(action,null);
  Message message=sentbox.getMessage(0);
  assertNotNull(message);
  assertEquals(contentTwoAttach,TestUtils.summaryzeContent(message).toString());
  Part part=MessageUtils.handleMultiPart(logger,message.getContent(),"uploadedFile_1.bin");
  assertTrue(part.getSize() > 0);
}
 

Example 9

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

Source file: Email.java

  22 
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 10

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

Source file: MailSender.java

  22 
vote

/** 
 * Sends a simple mail message.
 * @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 body the message content.
 * @throws ConnectionException if unable to construct the mail message or tosend out the message.
 */
public void send(String from,String to,String cc,String subject,String body) throws ConnectionException {
  Message msg=createMessage(to,from,cc,subject);
  if (body != null) {
    try {
      msg.setText(body);
      msg.saveChanges();
    }
 catch (    Exception e) {
      throw new ConnectionException("Unable to construct the body part of the mail message",e);
    }
  }
  send(msg);
}
 

Example 11

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

Source file: MessageWrapperContentTest.java

  22 
vote

@Test public void test() throws MessagingException, IOException {
  Message message=createMessage(String.format(sourceFilePath,fileNum));
  String body;
  if (message.getContentType().startsWith("multipart")) {
    Multipart mp=(Multipart)message.getContent();
    body=getText(mp);
  }
 else {
    body=(String)message.getContent();
  }
  assertBody(String.format(expectedFilePath,fileNum),body,encoding,checkCondition);
}
 

Example 12

From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/util/.

Source file: EmailUtils.java

  22 
vote

/** 
 * Send an email to a recipient
 * @param to of type String
 * @param from of type String
 * @param subject of type String
 * @param text of type String
 * @param mailProps of type Properties
 * @throws javax.mail.MessagingException
 */
public static void send(String to,String from,String subject,String text,Properties mailProps) throws MessagingException {
  Session mailSession=Session.getDefaultInstance(mailProps);
  Message simpleMessage=new MimeMessage(mailSession);
  InternetAddress fromAddress=new InternetAddress(from);
  InternetAddress toAddress=new InternetAddress(to);
  simpleMessage.setFrom(fromAddress);
  simpleMessage.setRecipient(Message.RecipientType.TO,toAddress);
  simpleMessage.setSubject(subject);
  simpleMessage.setText(text);
  Transport.send(simpleMessage);
}
 

Example 13

From project nuxeo-cmf, under directory /nuxeo-case-management-api/src/main/java/org/nuxeo/cm/mail/actionpipe/.

Source file: EndAction.java

  22 
vote

public boolean execute(ExecutionContext context) throws Exception {
  try {
    Message message=context.getMessage();
    message.setFlag(Flag.FLAGGED,false);
    return true;
  }
 catch (  Exception e) {
    log.error("Failed to execute EndAction",e);
    return false;
  }
}
 

Example 14

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

Source file: Mailman.java

  21 
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 15

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

Source file: BasicMailManager.java

  21 
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 16

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

Source file: Mailer.java

  21 
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 17

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

Source file: MailService.java

  21 
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 18

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

Source file: FeedbackRequestHandler.java

  21 
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 19

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

Source file: EmailSummaryNotifier.java

  21 
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 20

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

Source file: DecodeEmailTask.java

  21 
vote

@Override public void run(){
  log.info("Checking email...");
  Session session=Session.getInstance(sessionProperties,emailAuthenticator);
  Store store=null;
  Folder inbox=null;
  try {
    store=session.getStore("pop3");
    store.connect();
    inbox=store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    int count=inbox.getMessageCount();
    if (count > 0) {
      log.info("Found " + count + " messages");
    }
    for (int i=1; i <= count; i++) {
      log.info("Processing message " + i);
      Message message=inbox.getMessage(i);
      processMessage(session,message);
    }
  }
 catch (  Throwable t) {
    log.log(Level.WARNING,"Unexpected error",t);
  }
 finally {
    closeResources(store,inbox);
  }
}
 

Example 21

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

Source file: MailService.java

  21 
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 22

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

Source file: JavaMailSender.java

  21 
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 23

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

Source file: Emailer.java

  21 
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 24

From project mail_1, under directory /impl/src/test/java/br/gov/frameworkdemoiselle/mail/core/.

Source file: MailerImplTest.java

  21 
vote

@Test public void sendHtmlEmailWithImportanceHigh(){
  try {
    PowerMock.mockStatic(Beans.class);
    PowerMock.mockStatic(LoggerProducer.class);
    EasyMock.expect(Beans.getReference(Config.class)).andReturn(new Config());
    Logger logger=PowerMock.createMock(Logger.class);
    logger.debug(EasyMock.anyObject(String.class));
    EasyMock.expectLastCall().anyTimes();
    logger.info(EasyMock.anyObject(String.class));
    EasyMock.expectLastCall().anyTimes();
    EasyMock.expect(LoggerProducer.create(Dispatcher.class)).andReturn(logger);
    PowerMock.replayAll();
    new MailImpl().to("[email protected]").from("[email protected]").body().html("<b>Testing Demoiselle Mail Componente</b>").importance().high().send();
    List<Message> inbox=Mailbox.get("[email protected]");
    Message message=inbox.get(0);
    MimeMultipart multipart=(MimeMultipart)message.getContent();
    String[] priority=message.getHeader(MailHeader.PRIORITY.headerValue());
    InternetAddress ia=(InternetAddress)message.getFrom()[0];
    MimeBodyPart part=(MimeBodyPart)multipart.getBodyPart(0);
    MimeMultipart m=(MimeMultipart)part.getContent();
    Assert.assertTrue(m.getBodyPart(0).getContentType().startsWith("text/html"));
    Assert.assertEquals("[email protected]",ia.getAddress());
    Assert.assertEquals(MessagePriority.HIGH.getPriority(),priority[0]);
    Assert.assertEquals("<b>Testing Demoiselle Mail Componente</b>",(m.getBodyPart(0).getContent()));
    Assert.assertEquals(1,inbox.size());
    inbox.clear();
  }
 catch (  AddressException e) {
    Assert.fail();
  }
catch (  IOException e) {
    Assert.fail();
  }
catch (  MessagingException e) {
    Assert.fail();
  }
}
 

Example 25

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

Source file: EmailServlet.java

  21 
vote

public static void sendEmail(String to,String from,String subject,String body){
  Properties props=new Properties();
  Session session=Session.getDefaultInstance(props,null);
  Message msg;
  try {
    msg=new MimeMessage(session);
    msg.setFrom(new InternetAddress(from,"Meetup Now"));
    msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to,"MeetupNow User"));
    msg.setSubject(subject);
    msg.setText(body);
    Transport.send(msg);
  }
 catch (  Exception e) {
  }
}
 

Example 26

From project ndg, under directory /ndg-server-core/src/main/java/br/org/indt/ndg/server/mail/.

Source file: EmailSender.java

  21 
vote

public void postMail(Email email) throws MessagingException {
  boolean debug=props.getProperty("javamail.debug").equalsIgnoreCase("true") ? true : false;
  Session session=Session.getDefaultInstance(sessionProps);
  session.setDebug(debug);
  Message msg=new MimeMessage(session);
  InternetAddress addressFrom=new InternetAddress(props.getProperty("smtp.mail.from"));
  Address arrayTo[]=new InternetAddress[email.getCollRecipient().size()];
  msg.setFrom(addressFrom);
  msg.setSubject(email.getSubject());
  msg.setContent(new String(email.getText()),"text/plain");
  StringBuffer mensagem=new StringBuffer();
  String linha;
  int i=-1;
  for (Iterator<String> iterator=email.getCollRecipient().iterator(); iterator.hasNext(); ) {
    arrayTo[++i]=new InternetAddress(iterator.next());
  }
  msg.setRecipients(Message.RecipientType.TO,arrayTo);
  Transport t=session.getTransport();
  try {
    t.connect(props.getProperty("mail.smtps.host"),new Integer(props.getProperty("mail.smtps.port")),props.getProperty("smtp.mail.user"),props.getProperty("smtp.mail.password"));
    t.sendMessage(msg,msg.getAllRecipients());
  }
 catch (  Exception e) {
    throw new MessagingException(e.getLocalizedMessage());
  }
 finally {
    t.close();
  }
}
 

Example 27

From project niravCS2103, under directory /CS2103/src/sendMail/.

Source file: Send.java

  21 
vote

/** 
 * function that sends the mail
 * @param recipients recipient of the mail
 * @param subject subject of the mail
 * @param message of the mail
 * @return true 
 */
public boolean sendMail(String recipients,String subject,String message){
  try {
    Properties props=new Properties();
    props.put("mail.smtp.host",SMTP_HOST);
    props.put("mail.smtp.auth","true");
    props.put("mail.debug","false");
    props.put("mail.smtp.ssl.enable","true");
    Session session=Session.getInstance(props,new SocialAuth());
    Message msg=new MimeMessage(session);
    InternetAddress from=new InternetAddress(FROM_ADDRESS,FROM_NAME);
    msg.setFrom(from);
    InternetAddress toAddress=new InternetAddress(recipients);
    msg.setRecipient(Message.RecipientType.TO,toAddress);
    msg.setSubject(subject);
    msg.setContent(message,"text/html");
    Transport.send(msg);
    return true;
  }
 catch (  UnsupportedEncodingException ex) {
    return false;
  }
catch (  MessagingException e) {
    return false;
  }
}
 

Example 28

From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/ant/.

Source file: Mailer.java

  21 
vote

public void send(final String from,final String to,final String subject,final String content) throws AddressException, MessagingException {
  Session session=Session.getDefaultInstance(props,null);
  Message msg=new MimeMessage(session);
  msg.setFrom(new InternetAddress(from));
  String[] toAddresses=to.split(",");
  for (int i=0; i < toAddresses.length; i++) {
    msg.setRecipient(Message.RecipientType.TO,new InternetAddress(toAddresses[i]));
  }
  msg.setSubject(subject);
  msg.setText(content);
  if (auth) {
    Transport transport=session.getTransport("smtp");
    transport.connect(host,port,username,password);
    msg.saveChanges();
    transport.sendMessage(msg,msg.getAllRecipients());
    transport.close();
  }
 else {
    Transport.send(msg);
  }
}
 

Example 29

From project Possom, under directory /war/src/main/java/no/sesat/search/http/servlet/.

Source file: SendMailServlet.java

  21 
vote

protected void doGet(final HttpServletRequest req,final HttpServletResponse res) throws ServletException, IOException {
  final DataModel datamodel=(DataModel)req.getSession().getAttribute(DataModel.KEY);
  final Properties props=datamodel.getSite().getSiteConfiguration().getProperties();
  final String emailFrom=req.getParameter("emailFrom");
  final String emailTo=req.getParameter("emailTo");
  String name=req.getParameter("mailName");
  if (name.trim().equals("")) {
    name="ukjent";
  }
  String phone=req.getParameter("phone");
  if (phone.trim().equals("")) {
    phone="";
  }
 else {
    phone=" - tlf: " + phone;
  }
  try {
    final InternetAddress from=new InternetAddress(emailFrom);
    final InternetAddress to=new InternetAddress(emailTo);
    final Session session=Session.getDefaultInstance(props);
    final Message msg=new MimeMessage(session);
    final String txt=req.getParameter("text") + "\n\n\n" + "Denne foresp?rselen er sendt via Sesam bedriftss?k (http://www.sesam.no)";
    msg.setSubject("Kontaktskjema Sesam fra " + name + phone);
    msg.setText(txt);
    msg.setFrom(from);
    msg.addRecipient(MimeMessage.RecipientType.TO,to);
    Transport.send(msg);
  }
 catch (  MessagingException e) {
    LOG.error(e.getMessage(),e);
  }
  final String redir=req.getContextPath() + req.getParameter("rdir");
  res.sendRedirect(redir);
}
 

Example 30

From project skalli, under directory /org.eclipse.skalli.core/src/main/java/org/eclipse/skalli/core/internal/mail/.

Source file: MailServiceImpl.java

  21 
vote

private void sendMailInternal(Address[] rcptTo,Address[] rcptCC,Address[] rcptBCC,Address from,String subject,String body){
  try {
    String mailHost="mail.sap.corp";
    Properties props=System.getProperties();
    props.put("mail.smtp.host",mailHost);
    Session session=Session.getInstance(props,null);
    Message message=new MimeMessage(session);
    message.setFrom(from);
    if (rcptTo != null && rcptTo.length > 0) {
      message.setRecipients(Message.RecipientType.TO,rcptTo);
    }
    if (rcptCC != null && rcptCC.length > 0) {
      message.setRecipients(Message.RecipientType.CC,rcptCC);
    }
    if (rcptBCC != null && rcptBCC.length > 0) {
      message.setRecipients(Message.RecipientType.BCC,rcptBCC);
    }
    message.setSubject(subject);
    message.setContent(body,"text/plain");
    Transport.send(message);
  }
 catch (  AddressException e) {
    throw new RuntimeException(e);
  }
catch (  MessagingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 31

From project subsonic, under directory /subsonic-backend/src/main/java/net/sourceforge/subsonic/backend/service/.

Source file: EmailSession.java

  21 
vote

public void sendMessage(String from,List<String> to,List<String> cc,List<String> bcc,List<String> replyTo,String subject,String text) throws MessagingException {
  Message message=new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setReplyTo(new Address[]{new InternetAddress(from)});
  message.setRecipients(Message.RecipientType.TO,convertAddress(to));
  message.setRecipients(Message.RecipientType.CC,convertAddress(cc));
  message.setRecipients(Message.RecipientType.BCC,convertAddress(bcc));
  message.setReplyTo(convertAddress(replyTo));
  message.setSubject(subject);
  message.setText(text);
  Transport transport=null;
  try {
    transport=session.getTransport("smtps");
    transport.connect(USER,password);
    transport.sendMessage(message,message.getAllRecipients());
  }
  finally {
    if (transport != null) {
      transport.close();
    }
  }
}
 

Example 32

From project subsonic_1, under directory /subsonic-backend/src/main/java/net/sourceforge/subsonic/backend/service/.

Source file: EmailSession.java

  21 
vote

public void sendMessage(String from,List<String> to,List<String> cc,List<String> bcc,List<String> replyTo,String subject,String text) throws MessagingException {
  Message message=new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setReplyTo(new Address[]{new InternetAddress(from)});
  message.setRecipients(Message.RecipientType.TO,convertAddress(to));
  message.setRecipients(Message.RecipientType.CC,convertAddress(cc));
  message.setRecipients(Message.RecipientType.BCC,convertAddress(bcc));
  message.setReplyTo(convertAddress(replyTo));
  message.setSubject(subject);
  message.setText(text);
  Transport transport=null;
  try {
    transport=session.getTransport("smtps");
    transport.connect(USER,password);
    transport.sendMessage(message,message.getAllRecipients());
  }
  finally {
    if (transport != null) {
      transport.close();
    }
  }
}
 

Example 33

From project subsonic_2, under directory /subsonic-backend/src/main/java/net/sourceforge/subsonic/backend/service/.

Source file: EmailSession.java

  21 
vote

public void sendMessage(String from,List<String> to,List<String> cc,List<String> bcc,List<String> replyTo,String subject,String text) throws MessagingException {
  Message message=new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setRecipients(Message.RecipientType.TO,convertAddress(to));
  message.setRecipients(Message.RecipientType.CC,convertAddress(cc));
  message.setRecipients(Message.RecipientType.BCC,convertAddress(bcc));
  message.setReplyTo(convertAddress(replyTo));
  message.setSubject(subject);
  message.setText(text);
  Transport transport=null;
  try {
    transport=session.getTransport("smtps");
    transport.connect(USER,password);
    transport.sendMessage(message,message.getAllRecipients());
  }
  finally {
    if (transport != null) {
      transport.close();
    }
  }
}
 

Example 34

From project tapx, under directory /tapx-templating/src/test/java/com/howardlewisship/tapx/templating/integration/.

Source file: SendMail.java

  21 
vote

public static void main(String[] args) throws Exception {
  TemplateAPI templateAPI=new TemplateAPI("app2",new File("src/test/context.2"));
  TemplateRenderer renderer=templateAPI.createRenderer("ClasspathAssets","en","default");
  RenderedStream renderedStream=renderer.render();
  Properties props=new Properties();
  props.put("mail.smtp.host","smtp.comcast.net");
  props.put("mail.from","[email protected]");
  props.put("mail.user","hlship");
  props.put("mail.password",System.getProperty("mail.password"));
  props.put("mail.debug","true");
  Session session=Session.getInstance(props,null);
  Message message=new MimeMessage(session);
  message.setFrom();
  message.setSubject("Test message " + new Date());
  message.setSentDate(new Date());
  message.addRecipient(Message.RecipientType.TO,new InternetAddress(TO));
  templateAPI.getRegistry().getService(MailMessagePreparer.class).prepareMessage(message,renderedStream);
  Transport.send(message);
  templateAPI.shutdown();
}
 

Example 35

From project twistDemo, under directory /twist-libs/com.thoughtworks.webdriver.recorder_1.0.0.11288/sahi/src/net/sf/sahi/ant/.

Source file: Mailer.java

  21 
vote

public void send(final String from,final String to,final String subject,final String content) throws AddressException, MessagingException {
  Session session=Session.getDefaultInstance(props,null);
  Message msg=new MimeMessage(session);
  msg.setFrom(new InternetAddress(from));
  String[] toAddresses=to.split(",");
  for (int i=0; i < toAddresses.length; i++) {
    msg.setRecipient(Message.RecipientType.TO,new InternetAddress(toAddresses[i]));
  }
  msg.setSubject(subject);
  msg.setText(content);
  if (auth) {
    Transport transport=session.getTransport("smtp");
    transport.connect(host,port,username,password);
    msg.saveChanges();
    transport.sendMessage(msg,msg.getAllRecipients());
    transport.close();
  }
 else {
    Transport.send(msg);
  }
}
 

Example 36

From project twitstreet, under directory /src/com/twitstreet/mail/.

Source file: MailMgrImpl.java

  21 
vote

@Override public void sendMail(String subject,String message) throws MessagingException {
  boolean debug=false;
  Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  Properties props=new Properties();
  props.put("mail.smtp.host",SMTP_HOST_NAME);
  props.put("mail.smtp.auth","true");
  props.put("mail.debug","true");
  props.put("mail.smtp.port",SMTP_PORT);
  props.put("mail.smtp.socketFactory.port",SMTP_PORT);
  props.put("mail.smtp.socketFactory.class",SSL_FACTORY);
  props.put("mail.smtp.socketFactory.fallback","false");
  Session session=Session.getDefaultInstance(props,new javax.mail.Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication(){
      return new PasswordAuthentication(configMgr.getMailDealer(),configMgr.getMailDealerPassword());
    }
  }
);
  session.setDebug(debug);
  Message msg=new MimeMessage(session);
  msg.setFrom();
  String[] recipients=configMgr.getMailRecipients();
  InternetAddress[] addressTo=new InternetAddress[recipients.length];
  for (int i=0; i < recipients.length; i++) {
    addressTo[i]=new InternetAddress(recipients[i]);
  }
  msg.setRecipients(Message.RecipientType.TO,addressTo);
  msg.setSubject(subject);
  msg.setContent(message,"text/plain;charset=UTF-8");
  Transport.send(msg);
}
 

Example 37

From project usergrid-stack, under directory /rest/src/test/java/org/usergrid/rest/management/.

Source file: RegistrationTest.java

  21 
vote

@Ignore @Test public void postCreateOrgAndAdmin() throws Exception {
  properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS,"false");
  properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS,"false");
  properties.setProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION,"true");
  properties.setProperty(PROPERTIES_SYSADMIN_EMAIL,"[email protected]");
  JsonNode node=postCreateOrgAndAdmin("test-org-1","test-user-1","Test User","[email protected]","testpassword");
  UUID owner_uuid=UUID.fromString(node.findPath("data").findPath("owner").findPath("uuid").getTextValue());
  List<Message> inbox=org.jvnet.mock_javamail.Mailbox.get("[email protected]");
  assertFalse(inbox.isEmpty());
  Message account_confirmation_message=inbox.get(0);
  assertEquals("User Account Confirmation: [email protected]",account_confirmation_message.getSubject());
  String token=getTokenFromMessage(account_confirmation_message);
  logger.info(token);
  String response=resource().path("/management/users/" + owner_uuid + "/confirm").get(String.class);
  logger.info(response);
  Message account_activation_message=inbox.get(1);
  assertEquals("User Account Activated",account_activation_message.getSubject());
}
 

Example 38

From project zoj, under directory /judge_server/src/main/cn/edu/zju/acm/onlinejudge/util/.

Source file: EmailService.java

  21 
vote

public static void sendEmail(String email,String title,String replyTo,String content) throws Exception {
  String smtpUser=ConfigManager.getValue("smtp_user");
  String smtpPassword=ConfigManager.getValue("smtp_password");
  String smtpHost=ConfigManager.getValue("smtp_host");
  Properties props=new Properties();
  props.put("mail.smtp.host",smtpHost);
  if (smtpUser != null && smtpUser.length() > 0) {
    props.put("mail.smtp.auth","true");
  }
  Session sendMailSession=Session.getInstance(props,null);
  Message newMessage=new MimeMessage(sendMailSession);
  newMessage.setFrom(new InternetAddress(replyTo));
  newMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(email));
  newMessage.setSubject(title);
  newMessage.setSentDate(new Date());
  newMessage.setText(content);
  Transport trans=sendMailSession.getTransport("smtp");
  if (smtpUser != null && smtpUser.length() > 0) {
    trans.connect(smtpHost,smtpUser,smtpPassword);
  }
 else {
    trans.connect();
  }
  trans.sendMessage(newMessage,newMessage.getRecipients(javax.mail.Message.RecipientType.TO));
  trans.close();
}
 

Example 39

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

Source file: MailHandler.java

  19 
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 40

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

Source file: Helpers.java

  19 
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 41

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 42

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

Source file: FeedbackTilePanel.java

  19 
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 43

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

Source file: MobileCompanyServer.java

  19 
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 44

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

Source file: CoverityMailSender.java

  19 
vote

private MimeMessage createEmptyMail(CoverityBuildAction action,BuildListener listener) throws MessagingException {
  MimeMessage msg=new MimeMessage(Mailer.descriptor().createSession());
  msg.setContent("","text/html");
  msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
  msg.setSentDate(new Date());
  Set<InternetAddress> rcp=new LinkedHashSet<InternetAddress>();
  if (recipients != null) {
    StringTokenizer tokens=new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
      String address=tokens.nextToken();
      try {
        rcp.add(new InternetAddress(address));
      }
 catch (      AddressException e) {
        e.printStackTrace(listener.error(e.getMessage()));
      }
    }
  }
  Set<User> culprits=action.getBuild().getCulprits();
  rcp.addAll(buildCulpritList(listener,culprits));
  msg.setRecipients(Message.RecipientType.TO,rcp.toArray(new InternetAddress[rcp.size()]));
  return msg;
}
 

Example 45

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

Source file: GMailSender.java

  19 
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 46

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

Source file: SMTPAppender.java

  19 
vote

/** 
 * Address message.
 * @param msg message, may not be null.
 * @throws MessagingException thrown if error addressing message. 
 * @since 1.2.14
 */
protected void addressMessage(final Message msg) throws MessagingException {
  if (from != null) {
    msg.setFrom(getAddress(from));
  }
 else {
    msg.setFrom();
  }
  if (replyTo != null && replyTo.length() > 0) {
    msg.setReplyTo(parseAddress(replyTo));
  }
  if (to != null && to.length() > 0) {
    msg.setRecipients(Message.RecipientType.TO,parseAddress(to));
  }
  if (cc != null && cc.length() > 0) {
    msg.setRecipients(Message.RecipientType.CC,parseAddress(cc));
  }
  if (bcc != null && bcc.length() > 0) {
    msg.setRecipients(Message.RecipientType.BCC,parseAddress(bcc));
  }
}
 

Example 47

From project email-preview, under directory /src/main/java/org/jasig/portlet/emailpreview/dao/javamail/.

Source file: JavamailAccountDaoImpl.java

  19 
vote

private List<EmailMessage> getEmailMessages(Folder mailFolder,int pageStart,int messageCount,Session session) throws MessagingException, IOException, ScanException, PolicyException {
  int totalMessageCount=mailFolder.getMessageCount();
  int start=Math.max(1,totalMessageCount - pageStart - (messageCount - 1));
  int end=Math.max(totalMessageCount - pageStart,1);
  Message[] messages=totalMessageCount != 0 ? mailFolder.getMessages(start,end) : new Message[0];
  long startTime=System.currentTimeMillis();
  FetchProfile profile=new FetchProfile();
  profile.add(FetchProfile.Item.ENVELOPE);
  profile.add(FetchProfile.Item.FLAGS);
  profile.add(FetchProfile.Item.CONTENT_INFO);
  mailFolder.fetch(messages,profile);
  if (log.isDebugEnabled()) {
    log.debug("Time elapsed while fetching message headers:" + (System.currentTimeMillis() - startTime));
  }
  List<EmailMessage> emails=new LinkedList<EmailMessage>();
  for (  Message currentMessage : messages) {
    EmailMessage emailMessage=wrapMessage(currentMessage,false,session);
    emails.add(emailMessage);
  }
  Collections.reverse(emails);
  return emails;
}
 

Example 48

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

Source file: ServletUtils.java

  19 
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 49

From project guj.com.br, under directory /src/net/jforum/api/integration/mail/pop/.

Source file: POPConnector.java

  19 
vote

/** 
 * Lists all available messages in the pop server
 * @return Array of {@link Message}'s
 */
public Message[] listMessages(){
  try {
    this.messages=this.folder.getMessages();
    return this.messages;
  }
 catch (  Exception e) {
    throw new MailException(e);
  }
}
 

Example 50

From project james, under directory /mailetcontainer-camel/src/main/java/org/apache/james/mailetcontainer/impl/.

Source file: JamesMailetContext.java

  19 
vote

/** 
 * Generates a bounce mail that is a bounce of the original message.
 * @param bounceText the text to be prepended to the message to describe the bounce condition
 * @return the bounce mail
 * @throws MessagingException if the bounce mail could not be created
 */
private MailImpl rawBounce(Mail mail,String bounceText) throws MessagingException {
  MimeMessage original=mail.getMessage();
  MimeMessage reply=(MimeMessage)original.reply(false);
  reply.setSubject("Re: " + original.getSubject());
  reply.setSentDate(new Date());
  Collection<MailAddress> recipients=new HashSet<MailAddress>();
  recipients.add(mail.getSender());
  InternetAddress addr[]={new InternetAddress(mail.getSender().toString())};
  reply.setRecipients(Message.RecipientType.TO,addr);
  reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString()));
  reply.setText(bounceText);
  reply.setHeader(RFC2822Headers.MESSAGE_ID,"replyTo-" + mail.getName());
  return new MailImpl("replyTo-" + mail.getName(),new MailAddress(mail.getRecipients().iterator().next().toString()),recipients,reply);
}
 

Example 51

From project japid42, under directory /app/cn/bran/play/.

Source file: Mail.java

  19 
vote

public static String getContent(Part message) throws MessagingException, IOException {
  if (message.getContent() instanceof String) {
    return message.getContentType() + ": " + message.getContent()+ " \n\t";
  }
 else   if (message.getContent() != null && message.getContent() instanceof Multipart) {
    Multipart part=(Multipart)message.getContent();
    String text="";
    for (int i=0; i < part.getCount(); i++) {
      BodyPart bodyPart=part.getBodyPart(i);
      if (!Message.ATTACHMENT.equals(bodyPart.getDisposition())) {
        text+=getContent(bodyPart);
      }
 else {
        text+="attachment: \n" + "\t\t name: " + (StringUtils.isEmpty(bodyPart.getFileName()) ? "none" : bodyPart.getFileName()) + "\n"+ "\t\t disposition: "+ bodyPart.getDisposition()+ "\n"+ "\t\t description: "+ (StringUtils.isEmpty(bodyPart.getDescription()) ? "none" : bodyPart.getDescription())+ "\n\t";
      }
    }
    return text;
  }
  if (message.getContent() != null && message.getContent() instanceof Part) {
    if (!Message.ATTACHMENT.equals(message.getDisposition())) {
      return getContent((Part)message.getContent());
    }
 else {
      return "attachment: \n" + "\t\t name: " + (StringUtils.isEmpty(message.getFileName()) ? "none" : message.getFileName()) + "\n"+ "\t\t disposition: "+ message.getDisposition()+ "\n"+ "\t\t description: "+ (StringUtils.isEmpty(message.getDescription()) ? "none" : message.getDescription())+ "\n\t";
    }
  }
  return "";
}
 

Example 52

From project jforum2, under directory /src/net/jforum/api/integration/mail/pop/.

Source file: POPConnector.java

  19 
vote

/** 
 * Lists all available messages in the pop server
 * @return Array of {@link Message}'s
 */
public Message[] listMessages(){
  try {
    this.messages=this.folder.getMessages();
    return this.messages;
  }
 catch (  Exception e) {
    throw new MailException(e);
  }
}
 

Example 53

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

Source file: Email.java

  19 
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 54

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

Source file: SMTPAppender.java

  19 
vote

/** 
 * Address message.
 * @param msg message, may not be null.
 * @throws MessagingException thrown if error addressing message. 
 * @since 1.2.14
 */
protected void addressMessage(final Message msg) throws MessagingException {
  if (from != null) {
    msg.setFrom(getAddress(from));
  }
 else {
    msg.setFrom();
  }
  if (replyTo != null && replyTo.length() > 0) {
    msg.setReplyTo(parseAddress(replyTo));
  }
  if (to != null && to.length() > 0) {
    msg.setRecipients(Message.RecipientType.TO,parseAddress(to));
  }
  if (cc != null && cc.length() > 0) {
    msg.setRecipients(Message.RecipientType.CC,parseAddress(cc));
  }
  if (bcc != null && bcc.length() > 0) {
    msg.setRecipients(Message.RecipientType.BCC,parseAddress(bcc));
  }
}
 

Example 55

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

Source file: SMTPAppender.java

  19 
vote

/** 
 * Address message.
 * @param msg message, may not be null.
 * @throws MessagingException thrown if error addressing message. 
 * @since 1.2.14
 */
protected void addressMessage(final Message msg) throws MessagingException {
  if (from != null) {
    msg.setFrom(getAddress(from));
  }
 else {
    msg.setFrom();
  }
  if (replyTo != null && replyTo.length() > 0) {
    msg.setReplyTo(parseAddress(replyTo));
  }
  if (to != null && to.length() > 0) {
    msg.setRecipients(Message.RecipientType.TO,parseAddress(to));
  }
  if (cc != null && cc.length() > 0) {
    msg.setRecipients(Message.RecipientType.CC,parseAddress(cc));
  }
  if (bcc != null && bcc.length() > 0) {
    msg.setRecipients(Message.RecipientType.BCC,parseAddress(bcc));
  }
}
 

Example 56

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

Source file: WikiMail.java

  19 
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 57

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

Source file: MessageConverter.java

  19 
vote

public EmailMessage convertMessage(Message m) throws MailException {
  emailMessage=new EmailMessage();
  try {
    emailMessage.setFromAddresses(MailUtility.getInternetAddressses(m.getFrom()));
    emailMessage.setToAddresses(MailUtility.getInternetAddressses(m.getRecipients(RecipientType.TO)));
    emailMessage.setCcAddresses(MailUtility.getInternetAddressses(m.getRecipients(RecipientType.CC)));
    emailMessage.setBccAddresses(MailUtility.getInternetAddressses(m.getRecipients(RecipientType.BCC)));
    emailMessage.setSubject(m.getSubject());
    emailMessage.setMessageId(m.getHeader("Message-ID")[0]);
    emailMessage.addHeaders(MailUtility.getHeaders(m.getAllHeaders()));
    if (m.getContentType().toLowerCase().contains("multipart/")) {
      addMultiPart((MimeMultipart)m.getContent());
    }
 else     if (m.isMimeType("text/plain")) {
      emailMessage.setTextBody((String)m.getContent());
    }
  }
 catch (  IOException e) {
    throw new MailException(e);
  }
catch (  MessagingException e) {
    throw new MailException(e);
  }
  return emailMessage;
}
 

Example 58

From project Mail-Pigeon, under directory /pigeon-common/src/main/java/com/trivago/mail/pigeon/mail/.

Source file: BounceFacade.java

  19 
vote

public boolean processBounce(Message msg){
  try {
    final String[] header=msg.getHeader("Diagnostic-Code");
    boolean isHardBounce=false;
    boolean isSoftBounce=false;
    if (header[1].startsWith("55")) {
      isHardBounce=true;
    }
 else     if (header[1].startsWith("45")) {
      isSoftBounce=true;
    }
    return isHardBounce || isSoftBounce;
  }
 catch (  MessagingException e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 59

From project OpenConext-teams, under directory /coin-teams-war/src/main/java/nl/surfnet/coin/teams/control/.

Source file: AddMemberController.java

  19 
vote

/** 
 * Sends an email based on the  {@link Invitation}
 * @param invitation {@link Invitation} that contains the necessary data
 * @param subject    of the email
 * @param inviter    {@link Person} who sends the invitation
 * @param locale     {@link Locale} for the mail
 */
protected void sendInvitationByMail(final Invitation invitation,final String subject,final Person inviter,final Locale locale){
  final String html=composeInvitationMailMessage(invitation,inviter,locale,"html");
  final String plainText=composeInvitationMailMessage(invitation,inviter,locale,"plaintext");
  MimeMessagePreparator preparator=new MimeMessagePreparator(){
    public void prepare(    MimeMessage mimeMessage) throws MessagingException {
      mimeMessage.addHeader("Precedence","bulk");
      mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(invitation.getEmail()));
      mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
      mimeMessage.setSubject(subject);
      MimeMultipart rootMixedMultipart=controllerUtil.getMimeMultipartMessageBody(plainText,html);
      mimeMessage.setContent(rootMixedMultipart);
    }
  }
;
  mailService.sendAsync(preparator);
}
 

Example 60

From project orion.server, under directory /bundles/org.eclipse.orion.server.useradmin/src/org/eclipse/orion/server/useradmin/.

Source file: UserEmailUtil.java

  19 
vote

public void sendEmail(String subject,String messageText,String emailAddress) throws URISyntaxException, IOException, CoreException {
  Session session=Session.getInstance(properties,null);
  InternetAddress from;
  try {
    from=new InternetAddress(PreferenceHelper.getString("mail.from","OrionAdmin"));
    InternetAddress to=new InternetAddress(emailAddress);
    MimeMessage message=new MimeMessage(session);
    message.setFrom(from);
    message.addRecipient(Message.RecipientType.TO,to);
    message.setSubject(subject);
    message.setText(messageText);
    Transport transport=session.getTransport("smtp");
    transport.connect(properties.getProperty("mail.smtp.host",null),properties.getProperty("mail.smtp.user",null),properties.getProperty("mail.smtp.password",null));
    transport.sendMessage(message,message.getAllRecipients());
    transport.close();
  }
 catch (  AddressException e) {
    throw new CoreException(new Status(IStatus.ERROR,UserAdminActivator.PI_USERADMIN,"",e));
  }
catch (  MessagingException e) {
    throw new CoreException(new Status(IStatus.ERROR,UserAdminActivator.PI_USERADMIN,"",e));
  }
}
 

Example 61

From project qcadoo, under directory /qcadoo-mail/src/test/java/com/qcadoo/mail/internal/.

Source file: MailServiceImplTest.java

  19 
vote

@Test public final void shouldSendPlainTextEmail() throws Exception {
  ArgumentCaptor<MimeMessage> mailMessageCaptor=ArgumentCaptor.forClass(MimeMessage.class);
  mailServiceImpl.sendEmail(DEFAULT_RECIPIENT,DEFAULT_SUBJECT,DEFAULT_BODY);
  verify(mailSender,Mockito.times(1)).send(mailMessageCaptor.capture());
  verify(mimeMessage).setFrom(new InternetAddress(DEFAULT_SENDER));
  verify(mimeMessage).setRecipient(Message.RecipientType.TO,new InternetAddress(DEFAULT_RECIPIENT));
  verify(mimeMessage).setSubject(DEFAULT_SUBJECT);
  verify(mimeMessage).setContent(DEFAULT_BODY,"text/html");
}
 

Example 62

From project scisoft-ui, under directory /uk.ac.diamond.scisoft/src/uk/ac/diamond/scisoft/feedback/.

Source file: FeedbackView.java

  19 
vote

public void sendMail(String mailServer,final String from,final String to,final String subject,final String messageBody,final String attachmentName,final File attachmentContent,IProgressMonitor monitor){
  monitor.beginTask("Sending feedback",2);
  monitor.worked(1);
  Properties props=System.getProperties();
  props.put("mail.smtp.host",mailServer);
  try {
    Session session=Session.getInstance(props,null);
    MimeMessage message=new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
    message.setSubject(subject);
    MimeBodyPart messageBodyPart=new MimeBodyPart();
    messageBodyPart.setText(messageBody);
    Multipart multipart=new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart=new MimeBodyPart();
    DataSource source=new FileDataSource(attachmentContent);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(attachmentName);
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    Transport.send(message);
    Display.getDefault().asyncExec(new Runnable(){
      @Override public void run(){
        MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),"Feedback Successfully Sent","Thank you for your contribution");
      }
    }
);
  }
 catch (  Exception e) {
    logger.error("Feedback email not sent",e);
    Display.getDefault().asyncExec(new Runnable(){
      @Override public void run(){
        MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),"Feedback not sent!","There appears to be no email service set up on this computer, and so we cannot automatically process your feedback.  Please go to www.dawnsci.org and register your problem there. (This is accessible form the welcome page)");
      }
    }
);
  }
  monitor.worked(1);
}
 

Example 63

From project seamless, under directory /util/src/main/java/org/seamless/util/mail/.

Source file: EmailSender.java

  19 
vote

public void send(Email email) throws MessagingException {
  Session session=createSession();
  MimeMessage msg=new MimeMessage(session);
  msg.setFrom(new InternetAddress(email.getSender()));
  InternetAddress[] receipients={new InternetAddress(email.getRecipient())};
  msg.setRecipients(Message.RecipientType.TO,receipients);
  msg.setSubject(email.getSubject());
  msg.setSentDate(new Date());
  msg.setContent(createContent(email));
  Transport transport=createConnectedTransport(session);
  transport.sendMessage(msg,msg.getAllRecipients());
  transport.close();
}
 

Example 64

From project Shepherd-Project, under directory /src/main/java/org/ecocean/.

Source file: NotificationMailer.java

  19 
vote

public void sendIt(String host3,String from3,String to3,String subject3,String text3,Vector images3){
  if (CommonConfiguration.sendEmailNotifications()) {
    if (!(host3.equals("None"))) {
      try {
        message.setFrom(new InternetAddress(from3));
        message.addRecipients(Message.RecipientType.TO,to3);
        message.setSubject(subject3);
        message.setText(text3);
        Transport.send(message);
      }
 catch (      Exception e) {
        e.printStackTrace();
        System.out.println("     from: " + from3);
        System.out.println("     to: " + to3);
      }
    }
  }
}
 

Example 65

From project SIARD-Val, under directory /SIARD-Val/external-sources/log4j-1.2.12/java/org/apache/log4j/net/.

Source file: SMTPAppender.java

  19 
vote

/** 
 * Activate the specified options, such as the smtp host, the recipient, from, etc. 
 */
public void activateOptions(){
  Properties props=new Properties(System.getProperties());
  if (smtpHost != null)   props.put("mail.smtp.host",smtpHost);
  Session session=Session.getInstance(props,null);
  msg=new MimeMessage(session);
  try {
    if (from != null)     msg.setFrom(getAddress(from));
 else     msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO,parseAddress(to));
    if (subject != null)     msg.setSubject(subject);
  }
 catch (  MessagingException e) {
    LogLog.error("Could not activate SMTPAppender options.",e);
  }
}
 

Example 66

From project SOAj, under directory /soaj-core/src/main/java/info/soaj/core/rf/.

Source file: SjcEmailRF.java

  19 
vote

/** 
 * This method sends an email message using JavaMail.
 * @param emailPO
 * @return boolean - 'True' indicates the message was successfully sent.
 */
protected boolean sendTextEmail(final SjcEmailPO emailPO){
  final String Method_Name="sendTextEmail";
  final Session session=instantiateSession(emailPO);
  final MimeMessage mimeMessage=new MimeMessage(session);
  try {
    mimeMessage.setText(emailPO.getEmailMessage());
    mimeMessage.setSubject(emailPO.getEmailSubject());
    mimeMessage.addRecipients(Message.RecipientType.TO,formatInternetAddresses(emailPO.getEmailRecipients()));
    if (emailPO.containsEmailCCs()) {
      mimeMessage.addRecipients(Message.RecipientType.CC,formatInternetAddresses(emailPO.getEmailCCs()));
    }
    if (emailPO.containsEmailBCCs()) {
      mimeMessage.addRecipients(Message.RecipientType.BCC,formatInternetAddresses(emailPO.getEmailBCCs()));
    }
    mimeMessage.setFrom(new InternetAddress(emailPO.getEmailFromAddress()));
    mimeMessage.setSentDate(new Date());
    Transport.send(mimeMessage);
  }
 catch (  final Exception e) {
    final StringBuilder message=new StringBuilder();
    message.append("\nTo: ");
    for (    final String recipient : emailPO.getEmailRecipients()) {
      message.append(recipient + " ");
    }
    message.append("\nFrom: ");
    message.append(emailPO.getEmailFromAddress());
    message.append("\nSubject: ");
    message.append(emailPO.getEmailSubject());
    message.append("\nMessage:\n");
    message.append(emailPO.getEmailMessage());
    final SjcExceptionPathPO exceptionPathPO=new SjcExceptionPathPO(SjcEmailRF.CLASS_NAME,Method_Name);
    exceptionPathPO.setSuppressEmailing(true);
    throw new SjcEmailEPC(exceptionPathPO,message.toString(),e);
  }
  return true;
}
 

Example 67

From project syncany, under directory /syncany/src/org/syncany/connection/plugins/imap/.

Source file: ImapTransferManager.java

  19 
vote

@Override public void upload(File localFile,RemoteFile remoteFile) throws StorageException {
  connect();
  try {
    if (find(remoteFile) != null) {
      if (logger.isLoggable(Level.INFO)) {
        logger.log(Level.INFO,"IMAP: No need to upload {0}. Already exists.",new Object[]{remoteFile.getName()});
      }
      return;
    }
    if (logger.isLoggable(Level.INFO)) {
      logger.log(Level.INFO,"IMAP: Uploading {0} to {1} ...",new Object[]{localFile,remoteFile.getName()});
    }
    MimeMessage msg=new MimeMessage(session);
    MimeMultipart multipart=new MimeMultipart();
    msg.setSubject(remoteFile.getName());
    msg.setFlag(Flag.SEEN,true);
    MimeBodyPart chunk=new MimeBodyPart();
    DataSource source=new FileDataSource(localFile.getAbsolutePath());
    chunk.setDataHandler(new DataHandler(source));
    chunk.setContentID("data");
    multipart.addBodyPart(chunk);
    msg.setContent(multipart);
    folder.appendMessages(new Message[]{msg});
  }
 catch (  MessagingException ex) {
    throw new StorageException(ex);
  }
}
 

Example 68

From project ticket2rock, under directory /src/main/java/de/ejb3buch/ticket2rock/messagedriven/.

Source file: StornoMailBean.java

  19 
vote

public void onMessage(Message msg){
  try {
    String subject=msg.getSubject();
    StringTokenizer tokenizer=new StringTokenizer(subject," ");
    String command=tokenizer.nextToken();
    if ("STORNO".equalsIgnoreCase(command)) {
      String bestellNrAsString=tokenizer.nextToken();
      int bestellnr=Integer.parseInt(bestellNrAsString);
      stornator.storniereBestellung(bestellnr);
      logger.info("Stornierung von Bestellnr. " + bestellnr + " durchgefuehrt");
    }
 else {
      logger.info("eMail Subject " + subject + " ist nicht zu verarbeiten");
    }
  }
 catch (  Exception e) {
    throw new EJBException(e);
  }
}
 

Example 69

From project trademaker, under directory /src/org/lifeform/util/.

Source file: SecureMailSender.java

  19 
vote

public void run(){
  try {
    Session mailSession=Session.getDefaultInstance(props);
    MimeMessage message=new MimeMessage(mailSession);
    message.setSubject(subject);
    message.setContent(content,"text/plain");
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(recipient));
    Transport transport=mailSession.getTransport();
    transport.connect(host,user,password);
    transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.close();
  }
 catch (  Exception e) {
  }
}
 

Example 70

From project zanata, under directory /zanata-war/src/main/java/org/zanata/log4j/.

Source file: ZanataSMTPAppender.java

  19 
vote

@Override public void activateOptions(){
  Session session=(Session)Component.getInstance("mailSession");
  msg=new MimeMessage(session);
  try {
    if (getFrom() != null) {
      msg.setFrom(getAddress(getFrom()));
    }
 else {
      msg.setFrom();
    }
    msg.setRecipients(Message.RecipientType.TO,parseAddress(getTo()));
  }
 catch (  MessagingException e) {
    LogLog.error("Could not activate SMTPAppender options.",e);
  }
}
 

Example 71

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/mail/.

Source file: SmtpSender.java

  19 
vote

public void sendMail(String subj,String body,String to,String from,String contentType) throws IOException {
  try {
    InternetAddress fromAddress=new InternetAddress(postprocessFrom(Check.notNull(from)));
    MimeMessage msg=new MimeMessage(getSession());
    msg.setFrom(fromAddress);
    msg.setRecipients(Message.RecipientType.TO,postprocessTo(Check.notNull(to)));
    msg.setSubject(postprocessSubject(subj));
    msg.setSentDate(new Date());
    Tuple2<String,String> bodyAndContentType=postprocessBody(body,contentType);
    msg.setText(bodyAndContentType.get0(),bodyAndContentType.get1());
    msg.setContent(body,Check.notNull(contentType));
    sendMessage(msg);
  }
 catch (  MessagingException e) {
    throw new IOException(e);
  }
}