Example usage for javax.mail Message setRecipient

List of usage examples for javax.mail Message setRecipient

Introduction

In this page you can find the example usage for javax.mail Message setRecipient.

Prototype

public void setRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Set the recipient address.

Usage

From source file:Main.java

public static void main(String[] args) {
    String from = "user@some-domain.com";
    String to = "user@some-domain.com";
    String subject = "Hi There...";
    String text = "How are you?";

    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.some-domain.com");
    properties.put("mail.smtp.port", "25");
    Session session = Session.getDefaultInstance(properties, null);

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);//from   w ww  . j  a  va2  s.c o  m
    message.setText(text);

    Transport.send(message);
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    Properties props = new Properties();
    props.put("mail.host", "mail.cloud9.net");

    Session mailConnection = Session.getInstance(props, null);
    Message msg = new MimeMessage(mailConnection);

    Address a = new InternetAddress("a@a.com", "A a");
    Address b = new InternetAddress("fake@java2s.com");

    msg.setContent("Mail contect", "text/plain");
    msg.setFrom(a);//from  w  w w .  j  av a2 s. co  m
    msg.setRecipient(Message.RecipientType.TO, b);
    msg.setSubject("subject");

    Transport.send(msg);
}

From source file:SendApp.java

public static void send(String smtpHost, int smtpPort, String from, String to, String subject, String content)
        throws AddressException, MessagingException {

    java.util.Properties props = new java.util.Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", "" + smtpPort);
    Session session = Session.getDefaultInstance(props, null);

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);/*www  . j  a  va2  s  .  c  o  m*/
    msg.setText(content);

    Transport.send(msg);
}

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override//from   ww w .  ja  va2 s  . c om
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Send mail to the given email id with the provided text and subject.
 * //from   w  w  w  .j  a  v  a2 s. c  o  m
 * @param recepientEmailId email id of the recepient
 * @param emailText text of the mail
 * @param subject subject of the mail
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 */
protected void sendMail(String recepientEmailId, String emailText, String subject)
        throws IdeasExchangeException, AddressException, MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    Message message = new MimeMessage(session);

    message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId));
    message.setFrom(new InternetAddress(getAdminMailId()));

    message.setText(emailText);
    message.setSubject(subject);

    Transport.send(message);
    log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject);
}

From source file:se.vgregion.mobile.services.SmtpErrorReportService.java

@Override
public void report(ErrorReport report) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    try {//  ww w.j a v  a  2s  . c  o  m
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress = new InternetAddress(to);

        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);

        String text = String.format(body, report.getPrinter().getName(), report.getDescription(),
                report.getReporter());
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("Failed sending error report via mail", e);
    }

}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

/**
 * Convenience method for creating an e-mail message from a set of message properties.
 *
 * @param session the mail Session instance to use
 * @param config the email configuration to use
 * @param recipientAddress the e-mail address of the recipient
 * @param subject the e-mail subject line
 * @param message the e-mail message body
 *
 * @return a Message instance/*from www. jav  a  2 s  . c  o m*/
 *
 * @since hobson-hub-api 0.1.6
 */
protected Message createMessage(Session session, EmailConfiguration config, String recipientAddress,
        String subject, String message) {
    if (config.getSenderAddress() == null) {
        throw new HobsonInvalidRequestException("No sender address specified; unable to execute e-mail action");
    } else if (recipientAddress == null) {
        throw new HobsonInvalidRequestException(
                "No recipient address specified; unable to execute e-mail action");
    } else if (subject == null) {
        throw new HobsonInvalidRequestException("No subject specified; unable to execute e-mail action");
    } else if (message == null) {
        throw new HobsonInvalidRequestException("No message body specified; unable to execute e-mail action");
    }

    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(config.getSenderAddress()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
        msg.setSubject(subject);
        msg.setText(message);

        return msg;
    } catch (MessagingException e) {
        throw new HobsonInvalidRequestException("Unable to create mail message", e);
    }
}

From source file:com.waveerp.sendMail.java

public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc, String strPath) throws Exception {

    String strResult = "OK";

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);
    props.put("mail.user", strUser);
    props.put("mail.password", strPass01);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/*from  ww w .  j  a v  a  2s  .c  o m*/
    };
    Session session = Session.getInstance(props, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(strSource));
    //InternetAddress[] toAddresses = { new InternetAddress(strDestination) };
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination));
    msg.setSubject(strSubject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(strMsg, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    //if (attachFiles != null && attachFiles.length > 0) {
    //    for (String filePath : attachFiles) {
    //        MimeBodyPart attachPart = new MimeBodyPart();
    //
    //        try {
    //            attachPart.attachFile(filePath);
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        }
    //
    //        multipart.addBodyPart(attachPart);
    //    }
    //}

    String fna;
    String fnb;
    URL fileUrl;

    fileUrl = null;
    fileUrl = this.getClass().getResource("sendMail.class");
    fna = fileUrl.getPath();
    fna = fna.substring(0, fna.indexOf("WEB-INF"));
    //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath );
    fnb = URLDecoder.decode(fna + strPath);

    MimeBodyPart attachPart = new MimeBodyPart();
    try {

        attachPart.attachFile(fnb);

    } catch (IOException ex) {

        //ex.printStackTrace();
        strResult = ex.getMessage();

    }
    multipart.addBodyPart(attachPart);

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

    return strResult;

}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail./*  www  .  j a  va 2  s. com*/
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:mail.MailService.java

/**
 * Erstellt eine kanonisierte MIME-Mail.
 * @param email//from  ww  w.ja v  a2s .com
 * @throws MessagingException
 * @throws IOException
 */
public String createMail2(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    int laenge = mailAsBytes.length + getCRLF().length;
    byte[] bOout = new byte[laenge];
    for (int i = 0; i < mailAsBytes.length; i++) {
        bOout[i] = mailAsBytes[i];
    }

    byte[] neu = getCRLF();
    int counter = 0;
    for (int i = mailAsBytes.length; i < laenge; i++) {
        bOout[i] = neu[counter];
        counter++;
    }

    email.setText(bOout);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(email.getText()));
    msg.saveChanges();
    /*       
           // Erstellen des Content
           MimeMultipart content = new MimeMultipart("text"); 
                  
           MimeBodyPart part = new MimeBodyPart(); 
           part.setText(email.getText()); 
           part.setHeader("MIME-Version" , "1.0"); 
           part.setHeader("Content-Type" , part.getContentType()); 
                   
           content.addBodyPart(part);
           System.out.println(content.getContentType());
                  
          Message msg = new MimeMessage(session); 
          msg.setContent(content); 
          msg.setHeader("MIME-Version" , "1.0"); 
          msg.setHeader("Content-Type" , content.getContentType()); 
            
          InternetAddress addressFrom = new InternetAddress(email.getAbsender()); 
           msg.setFrom(addressFrom); 
                   
           InternetAddress addressTo = new InternetAddress(email.getEmpfnger()); 
           msg.setRecipient(Message.RecipientType.TO, addressTo); 
                   
           msg.setSubject(email.getBetreff());
           msg.setSentDate(email.getAbsendeDatum()); */

    //msg.setContent(email.getText(), "text/plain");

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 2");
        throw e;
    }
    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}