gpt4 book ai didi

grails - 将Java sendEmail方法转换为Groovy

转载 作者:行者123 更新时间:2023-12-02 14:39:39 25 4
gpt4 key购买 nike

我有一个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()
}
}

最佳答案

这种糟糕的支撑风格与Groovy不需要分号冲突。尽管不需要多次使用,但不需要非匿名类定义,只需这样声明即可:

FileDataSource fileDataSource = new FileDataSource(filename) {
String getContentType() { 'application/octet-stream' }
}

关于grails - 将Java sendEmail方法转换为Groovy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com