SMTP Messaging client with file attachment

PBelandPBeland Posts: 14

Hi!
I was please to discover that it is really easy to send an email using a Messaging client tool. I want to test a workflow that is started when an email is received. Anybody knows if it is possible to add attachments to the email? Additional headers or ways to format the request???

Thanks!

Tagged:

Comments

  • benken_parasoftbenken_parasoft Posts: 491 ✭✭✭

    The built-in SMTP transport is very simple, limited to sending text/plain and not multipart/form-data. You would probably need to script this. I recommend using the JavaMail (javax.mail) API.

  • PBelandPBeland Posts: 14

    Starting from a few examples on the net, I made this bit of code that works...

    import com.parasoft.api.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    
    boolean sendMail(Object input, ExtensionToolContext context) {
    
        host = "mail.foo.com";
        port = 25;
        user = "username";
        pass = "password";
    
        from = "[email protected]";
        to = "[email protected]";
        subject = "Groovy mail with attachment";
        body = "Here's your file";
    
    
        Properties props = System.getProperties();
    /*    props.put("mail.smtp.starttls.enable",true);
        // mail.smtp.ssl.trust is needed in script to avoid error "Could not convert socket to TLS"
        props.setProperty("mail.smtp.ssl.trust", host);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.user", user);
        props.put("mail.smtp.password", pass);
    */
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port); 
        Session session = Session.getDefaultInstance(props, null);
    
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
    
        Multipart multipart = new MimeMultipart();
    
        // Part one - Body
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        multipart.addBodyPart(messageBodyPart);
    
        // Part two - attachment
        MimeBodyPart attPart = new MimeBodyPart();
        DataSource source = new FileDataSource(context.getAbsolutePathFile(".\\File1.pdf"));
        attPart.setDataHandler(new DataHandler(source));
        attPart.setFileName("AttachedPDF.pdf");
        multipart.addBodyPart(attPart);
    
        // Put parts in message
        message.setContent(multipart);
    
        Transport transport = session.getTransport("smtp");
        transport.connect(/*host, user, pass*/);
    
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    
        return true;
    }
    
Sign In or Register to comment.