【发布时间】:2017-11-13 20:32:15
【问题描述】:
我有一个通过电子邮件发送文件附件的 Java 方法。我正在尝试将它作为 Grails 应用程序的一部分移植到 Groovy。我对FileDataSource 声明的格式有疑问。违规代码标有星号。在 Groovy 中执行该部分的正确方法是什么?我似乎在网上找不到任何东西。
public static void sendEmail(String sendFile)
{
//
// Send the log file via email.
//
final String username = "myname@mydomain.com"
final String password = "mypassword"
// Strings that contain from, to, subject, body and file path to the attachment
String from = username;
String subject = "Test Results"
String body = "Body of Test Results email."
String filename = sendFile
// Set smtp properties
Properties properties = new Properties()
properties.put("mail.smtp.starttls.enable", "true")
properties.put("mail.smtp.auth", "true")
properties.put("mail.smtp.host", "smtp.gmail.com")
properties.put("mail.smtp.port", "587")
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username,password)
}
});
try
{
MimeMessage message = new MimeMessage(session)
message.setFrom(new InternetAddress(from))
// For debug uncomment the line below and enter your email address.
//message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("peter.cook@studentuniverse.com"));
// For debug comment the line below out.
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("cccm@studentuniverse.com,WebsiteOperations@studentuniverse.com,peter.cook@studentuniverse.com"))
message.setSubject(subject)
message.setSentDate(new Date())
// Set the email body
MimeBodyPart messagePart = new MimeBodyPart()
messagePart.setText(body)
// Set the email attachment file
MimeBodyPart attachmentPart = new MimeBodyPart()
*FileDataSource fileDataSource = new FileDataSource(filename)
*{
* @Override
* public String getContentType()
* {
* return "application/octet-stream"
* }
* }
attachmentPart.setDataHandler(new DataHandler(fileDataSource))
attachmentPart.setFileName(fileDataSource.getName())
// Add all parts of the email to Multipart object
Multipart multipart = new MimeMultipart()
multipart.addBodyPart(messagePart)
multipart.addBodyPart(attachmentPart)
message.setContent(multipart)
// Send email
Transport.send(message)
System.out.println("Mail sent!")
}
catch (MessagingException e)
{
e.printStackTrace()
}
}
【问题讨论】:
-
尝试将“{”与
new FileDataSource(filename)放在同一行。