I'm trying to send email with attachment by using gmail api. I coppied and added some changes to my code and try to send it.
Although sending text email was successful, sending mail with attachment is failed. The exception is triggered after writing from email to buffer.
no object DCH for MIME type multipart/mixed
here is my code
fun sendMail(
c: Context,
ac: Account,
from: String,
tos: List<String>,
subject: String,
content: String,
vararg f: File
) {
val props = Properties()
val session = Session.getDefaultInstance(props, null)
var email = MimeMessage(session)
try {
email.setFrom(InternetAddress(from));
for (to in tos) {
email.addRecipient(
javax.mail.Message.RecipientType.TO,
InternetAddress(to)
);
}
email.setSubject(subject);
var mimeBodyPart = MimeBodyPart();
mimeBodyPart.setContent(content, "text/plain");
val multipart = MimeMultipart()
multipart.addBodyPart(mimeBodyPart);
for (file in f) {
mimeBodyPart = MimeBodyPart();
var source: DataSource = FileDataSource(file)
mimeBodyPart.dataHandler = DataHandler(source)
mimeBodyPart.fileName = file.name;
}
multipart.addBodyPart(mimeBodyPart);
email.setContent(multipart);
var message = createMessageWithEmail(email)
val gmailService = getService(c, ac)
val returnedMessage = gmailService?.users()?.messages()?.send("me", message)?.execute()
message.id = returnedMessage?.id
message.labelIds = returnedMessage?.labelIds
println("returnedMessage : $returnedMessage");
println("currentMessage : " + message.toPrettyString())
} catch (e: MessagingException) {
Log.e(TAG, "sendMail: $e")
} catch (e: IOException) {
Log.e(TAG, "sendMail: $e")
}
}
fun createMessageWithEmail(emailContent: MimeMessage): Message {
val message = Message()
try {
val buffer = ByteArrayOutputStream()
emailContent.writeTo(buffer)
val bytes = buffer.toByteArray()
val encodedEmail = encodeBase64URLSafeString(bytes)
message.raw = encodedEmail
} catch (e: MessagingException) {
Log.e(TAG, "createMessageWithEmail: $e")
} catch (e: IOException) {
Log.e(TAG, "createMessageWithEmail: $e")
}
return message
}
I have tried to add Thread.currentThread().setContextClassLoader(javax.mail.Message::class.java.getClassLoader())
but it didnt solved.
I'm so confused about it. How does not the code which is in the documentation work? I don't understand what I'm missing.
I'm getting file from internal storage. I don't think it is about it. Can you help me what I'm missing? Thank you !