gpt4 book ai didi

java - 在 Java 中通过 Amazon 发送带附件的电子邮件的示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:56 24 4
gpt4 key购买 nike

有没有人有通过 Amazon SES(使用 Java)发送带有附件的电子邮件的示例?

最佳答案

可能有点晚了,但是你可以使用这段代码(你还需要 Java Mail):

public class MailSender
{
private Transport AWSTransport;
...
//Initialize transport
private void initAWSTransport() throws MessagingException
{
String keyID = <your key id>
String secretKey = <your secret key>
MailAWSCredentials credentials = new MailAWSCredentials();
credentials.setCredentials(keyID, secretKey);
AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
AWSsession = Session.getInstance(props);
AWStransport = new AWSJavaMailTransport(AWSsession, null);
AWStransport.connect();
}

public void sendEmail(byte[] attachment)
{
//mail properties
String senderAddress = <Sender address>;
String recipientAddress = <Recipient address>;
String subject = <Mail subject>;
String text = <Your text>;
String mimeTypeOfText = <MIME type of text part>;
String fileMimeType = <MIME type of your attachment>;
String fileName = <Name of attached file>;

initAWSTransport();

try
{
// Create new message
Message msg = new MimeMessage(AWSsession);
msg.setFrom(new InternetAddress(senderAddress));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
msg.setSubject(subject);

//Text part
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, mimeTypeOfText);
multipart.addBodyPart(messageBodyPart);

//Attachment part
if (attachment != null && attachment.length != 0)
{
messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachment,fileMimeType);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);

//send message
msg.saveChanges();
AWSTransport.sendMessage(msg, null);
} catch (MessagingException e){...}
}
}

关于java - 在 Java 中通过 Amazon 发送带附件的电子邮件的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7963439/

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