2

我正在尝试使用 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!"
4

2 回答 2

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
于 2013-08-07T14:58:15.027 回答
0

我通过以下步骤解决了同样的问题。

1- 解压mail.jar 文件(解压jar 文件com,javax,META-INF 后会得到以下文件夹) 2- 将上述所有文件夹放入classes 文件夹中 3- 重新启动您的网络服务器。

于 2013-12-19T12:08:15.150 回答