发送电子邮件:MIME类型multipart / mixed没有对象DCH

时间:2013-08-07 14:31:19

标签: groovy javamail mime groovy-console

我正在尝试使用Java代码发送电子邮件,但是从GroovyConsole运行。它适用于我只发送没有附件的电子邮件但是只要我添加附件的多部分逻辑就会失败。

编辑:我正在使用Javamail版本1.4.7

这是我遇到的错误。

javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed; 

boundary="----=_Part_16_24710054.1375885523061"

at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:891)

它发生在下面的Transport.send(mimeMsg)行上。

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;


Properties properties = new Properties()
Session session
MimeMessage mimeMsg 

properties.put("mail.smtp.host", "[my host ip]")

session = Session.getDefaultInstance(properties)
mimeMsg = new MimeMessage(session)

String recipient = "[to email address]"

mimeMsg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient))

mimeMsg.setSubject("This is the subject")
mimeMsg.setText("This is the message #1")

mimeMsg.setFrom(new InternetAddress("[from email address]"))

BodyPart messageBodyPart = new MimeBodyPart()
messageBodyPart.setText(mimeMsg.getContent())    
Multipart multipart = new MimeMultipart()

String filePath = "[full & correct path to test.txt]"
DataSource source = new FileDataSource(filePath)
messageBodyPart.setDataHandler(new DataHandler(source))

String fileName = "test.txt"
messageBodyPart.setFileName("test.txt")

multipart.addBodyPart(messageBodyPart)

mimeMsg.setContent(multipart)

Transport.send(mimeMsg)

println "Message Sent!"

2 个答案:

答案 0 :(得分:1)

我认为这是GroovyConsole运行方式的类加载器问题......

如果我将以下@Grab@GrabcConfig添加到脚本中,则可以正常运行...

@Grab( 'javax.mail:mail:1.4.7' )
@GrabConfig(systemClassLoader=true, initContextClassLoader=true)
import javax.mail.*
import javax.mail.internet.*
import javax.activation.*

def props = new Properties().with { p ->
    p.'mail.smtp.host' = 'my mail server'
    p
}

def session = Session.getDefaultInstance( props )

def message = new MimeMessage( session )

message.addRecipient( Message.RecipientType.TO, new InternetAddress( 'to address' ) )
message.subject = 'This is the subject'
message.text = 'This is the message #1'
message.from =  new InternetAddress( 'from address' )

def textpart = new MimeBodyPart()
textpart.text = 'This is the message #2'

def attachment = new MimeBodyPart()
attachment.dataHandler = new DataHandler( new FileDataSource( '/path/to/file.txt' ) )
attachment.fileName = 'file.txt'

def multi = new MimeMultipart()
multi.addBodyPart( textpart )
multi.addBodyPart( attachment )

message.content = multi

Transport.send( message )

或者,删除两个@Grab@GrabConfig行,然后从命令行运行它:

groovy -cp /path/to/mail-1.4.7.jar:/path/to/activation-1.1.jar mail.groovy

答案 1 :(得分:0)

我已按照以下步骤解决了同样的问题。

1-解压缩mail.jar文件(解压缩jar文件后,您将获得以下文件夹 COM,使用javax,META-INF) 2-将所有上述文件夹放在classes文件夹中 3-重新启动Web服务器。