我需要发送一封带有Excel文件附件的自定义电子邮件。我按照我在网上找到的指南进行操作,但不断收到此错误:javax.mail.internet.ParseException: Expected ';', got "charset"
message.writeTo(out)
。
我认为这可能与我对文本进行编码的方式有关。我不是 100% 确定该部分是否正确编写。
import com.amazonaws.auth.BasicAWSCredentials
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.Properties
import javax.activation.DataHandler
import javax.activation.FileDataSource
import javax.mail.Message
import javax.mail.Session
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
import javax.mail.internet.MimeUtility
import com.amazonaws.regions.Regions
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder
import com.amazonaws.services.simpleemail.model.RawMessage
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest
import java.io.File
import java.lang.System.out
.
.
.
.
fun sendEmail(){
val file = File("test.xlsx")
try{
val defaultCharSet = MimeUtility.getDefaultJavaCharset()
val session = Session.getDefaultInstance(Properties())
val message = MimeMessage(session)
message.setSubject(EMAIL_SUBJECT, "UTF-8")
message.setFrom(InternetAddress(EMAIL_FROM))
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_TO))
val msg_body = MimeMultipart("alternative")
val wrap = MimeBodyPart()
val textPart = MimeBodyPart()
textPart.setContent(MimeUtility
.encodeText(EMAIL_TEXT_BODY,defaultCharSet,"B"), "text/plain charset=UTF-8")
textPart.setHeader("Content-Transfer-Encoding", "base64")
val htmlPart = MimeBodyPart()
htmlPart.setContent(MimeUtility
.encodeText(EMAIL_BODY_HTML,defaultCharSet,"B"),"text/html charset=UTF-8")
htmlPart.setHeader("Content-Transfer-Encoding", "base64")
msg_body.addBodyPart(textPart)
msg_body.addBodyPart(htmlPart)
wrap.setContent(msg_body)
val msg = MimeMultipart("mixed")
message.setContent(msg)
msg.addBodyPart(wrap)
val att = MimeBodyPart()
val fds = FileDataSource(file)
att.dataHandler = DataHandler(fds)
att.fileName = fds.name
msg.addBodyPart(att)
val client = AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build()
message.writeTo(out)
val outputStream = ByteArrayOutputStream()
message.writeTo(outputStream)
val rawMessage = RawMessage(ByteBuffer.wrap(outputStream.toByteArray()))
val rawEmailRequest = SendRawEmailRequest(rawMessage)
client.sendRawEmail(rawEmailRequest)
println("Email sent")
}catch (e: Exception){
println("Email failed to send with error: ${e.message}")
println(e.printStackTrace())
}
}
您的 MIME 类型语法错误。 而且您的代码过于复杂。 试试这个:
val textPart = MimeBodyPart()
textPart.setText(EMAIL_TEXT_BODY, "utf-8")
val htmlPart = MimeBodyPart()
htmlPart.setText(EMAIL_BODY_HTML, "utf-8", "html")
而且您不需要对文本进行编码或设置内容传输编码标头,JavaMail 将为您完成所有这些操作。