0

I have used the java mail API to send emails within our group. I am aware of the DataHandler objects that in turn uses FileDataSource to grab the files and attach as a multipart file. However, I am not able to use it in scala. Can anyone help me on this?

Heres my code:

def createMessage: Message = {
val properties = new Properties()
properties.put("mail.smtp.host", smtpHost)
properties.put("mail.smtp.port",smtpPort)
val session = Session.getDefaultInstance(properties, null)
return new MimeMessage(session)

}

var message: Message = null

  message = createMessage
  message.setFrom(new InternetAddress(from))
  message.setSentDate(new Date())
  message.setSubject(subject)
  message.setText(content)
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(to))

  def sendMessage {
    Transport.send(message)
  }

I can use message.sefileName to set file name of the attachment, but how can I attach the actual files. For example in Java, we can achieve similar results like the following:

MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
FileDataSource fdatasource = new FileDataSource(file);
messageBodyPart2.setDataHandler(new DataHandler(fdatasource));
messageBodyPart2.setFileName(fdatasource.getName)
Multipart mpart = new MimeMultipart();
mpart.addBodyPart(messageBodyPart1);
mpart.addBodyPart(messageBodyPart2);
message.setContent(mpart);
user1234
  • 1
  • 2
  • I don't know Scala, but you might find it easier to use the [attachFile](https://javaee.github.io/javamail/docs/api/javax/mail/internet/MimeBodyPart.html#attachFile-java.io.File-) method. You're still going to need to create MimeMultipart and MimeBodyPart objects, of course. – Bill Shannon Dec 27 '18 at 20:36

1 Answers1

0

I don't know this mail API, but you should be able to use a Java API the same way in Scala that you would use it in Java. If you see something like this in Java:

MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(messageText);

You usually want to translate it to something like this in Scala:

val messageBodyPart1: MimeBodyPart = new MimeBodyPart()
messageBodyPart1.setText(messageText)

Just translate the Java code you have posted to Scala this way and it should work as well (or not well) as it worked in Java.

Toxaris
  • 7,156
  • 1
  • 21
  • 37