Apache commons Email Alias Not working Properly in scala - scala

I am using HtmlEmail Class of ApacheCommons for sending HTML formatted email with embedded images
Apache Commons Email API (v1.4) is used in my Scala project
I am not Seeing the Alias (MY REPORTS) as sender name in my Received Email
Following is my Function
#throws(classOf[EmailException])
#throws(classOf[Exception])
def createHTMLEmailMessage(htmlContent: String): EmailMessage = {
val email = new HtmlEmail
// alternative message if the client does not support html
email.setHtmlMsg(htmlContent)
email.addTo("TO_address#gmail.com")
email.setFrom("MY_address#GMAIL.com", "MY REPORTS")
email.setHostName("MY_HOSTNAME")
email.setSmtpPort(587)
email.setAuthentication("USERNAME","PASSWORD")
email.setStartTLSEnabled(true)
email.setSSLOnConnect(false)
email.setSubject("Subject")
val emailMsg = EmailMessage(email)
emailMsg
}

Related

How to specify file name for a download done via POST in akka http

The user sends a post request, than based on that post body I create an Excel file (.xlsx) and want to send that file back, without storage of that file itself.
def writeAsync(out: OutputStream): Unit = {
Future {
val wb = new XSSFWorkbook
val sheet1: Sheet = wb.createSheet("sheet1");
val os = new ByteArrayOutputStream()
wb.write(os)
os.writeTo(out)
out.close()
wb.close()
}
}
...
pathPrefix("createAndDownloadExcel") {
post {
...
val generatedFileName = "customGeneratedFileName.xlsx" // <-- this name should the file name be like
val (out, source) = StreamConverters.asOutputStream().preMaterialize()
writeAsync(out)
complete(HttpEntity(ContentTypes.`application/octet-stream`, source))
}
}
The response has the excel content with the file name: "createAndDownloadExcel", but I would like it to have the file name based on the individual generated file name.
The name will be later manually generated based on the POST body, whereby a simple change in pathPrefix("fixedName.xlsx") does not work for my needs.
How can I solve this, being able to give a dynamic file name for that returned OutputStream?
"org.apache.poi" % "poi-ooxml" % "5.2.0"
Try adding response header Content-Disposition.
The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present).
import akka.http.scaladsl.model.headers.ContentDispositionTypes.attachment
import akka.http.scaladsl.model.headers.`Content-Disposition`
....
respondWithHeader(`Content-Disposition`(attachment, Map("filename" -> "customGeneratedFileName.xlsx"))) {
complete(HttpEntity(ContentTypes.`application/octet-stream`, source))
}

send email with multiple attachment in scala

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);
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.

Sendgrid template not set using setTemplateId

I'm not able to use template id for email body in email sent from sendgrid with following code (using 2.2):
val sendgrid = new SendGrid(sendgridapikey)
val sendgridEmail = new SG.Email()
sendgridEmail.setSubject("Invitation Email")
sendgridEmail.setFromName("Sender")
sendgridEmail.setTemplateId("6305c994-af9a-432e-9a07-5d7f493800e1")
sendgridEmail.setFrom("no-reply#domain.com")
sendgridEmail.addTo(to)
val response = sendgrid.send(sendgridEmail)
The email is sent if I remove setTemplateId line above but not with that.
Please help. thanks!

Play Framework [play-mailer]: how to ensure each receiver sees only his or her email address in the TO field

Here below is the code to send an email with play-mailer:
import play.api.libs.mailer._
...
val email = Email(
"My Subject",
"Me <j3d#domain.com>",
Seq("john#domain.com", "joe#domain.com", "jack#domain.com"),
bodyText = Some("Some text..."),
bodyHtml = Some("<p>Some text...</p>")
)
MailerPlugin.send(email)
The problem is that receivers see all the recipients the email was sent to. Of course, an option could be to invoke MailerPlugin.send for every single recipient... but I'm wondering if there is a better way to ensure each receiver sees only his or her email address in the to field.
Perhaps the best solution will be using hidden recepient which aka BCC. Emailer plugin has method addBcc(String address):
public void addBcc(String address) {
this.bcc.add(address);
}
Regards!

Send multiple attachments with Grails Async Mail Plugin

I am using grails Async Mail plugin to send emails with attachments in my app. to achieve that I have written following code
def sendEmail = {
def documentsInstances = Documents.getAll(params.list('ids[]'))
def s3Service = new AmazonS3Service()
documentsInstances.each(){documentsInstance->
asyncMailService.sendMail {
multipart true
to documentsInstance.author.emailAddress
subject 'Test';
html '<body><u>Test</u></body>';
attachBytes documentsInstance.filename , 'text/plain', s3Service.getBytes(session.uid,documentsInstance.filename);
}
}//
}
Now the code above works pretty much correctly but it sends an email per attachment, I am not sure how can I move this loop inside send mail so that I can send multiple attachments in an email.
Also is there a way to send an email so that I don't have to load a whole file in byte[]?
I am using JetS3t for access to Amazon S3 and I tried "attach" method with
new InputStreamResource(s3Obj.getDataInputStream()) ie
attach documentsInstance.filename , 'text/plain', new InputStreamResource(s3Obj.getDataInputStream());
but I am getting
"Passed-in Resource contains an open stream: invalid argument. JavaMail requires an InputStreamSource that creates a fresh stream for every call"
You need your loop inside the email:
def sendEmail = {
def documentsInstances = Documents.getAll(params.list('ids[]'))
def s3Service = new AmazonS3Service()
asyncMailService.sendMail {
multipart true
to documentsInstance.author.emailAddress
subject 'Test';
html '<body><u>Test</u></body>';
// loop over attachments
documentsInstances.each{ documentsInstance->
attachBytes documentsInstance.filename , 'text/plain', s3Service.getBytes(session.uid, documentsInstance.filename);
}
}
}
This should attach multiple files.
If it throws an error about not being able to find an attachBytes method, you might need to explicitly call owner.attachBytes instead, which should refer to the outer sendMail closure.
Update based on comments:
The Async plugin looks like it defers to the normal mail plugin. The normal mail plugin's docs describes how to use multiple attachments.
This would look something like:
// loop over attachments
documentsInstances.each{ documentsInstance->
attach documentsInstance.filename , 'text/plain', s3Service.getBytes(session.uid, documentsInstance.filename);
//^^^^^^ Notice, just 'attach', not 'attachBytes'
}
I don't know the S3 plugin you are using, but if there is a way to retrieve an InputStreamSource from it, it appears that you can stream the bytes directly to the mail plugin, instead of loading them into memory.