发送电子邮件附件是一个常见的需求,可以通过使用电子邮件客户端或编写代码来实现。以下是一些常见的方法和步骤:
smtplib
和email
库发送附件。以下是一个简单的示例:import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
# 邮件发送者和收件人
from_addr = 'sender@example.com'
to_addr = 'recipient@example.com'
# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = '带附件的邮件'
# 添加邮件正文
body = '这是一个带附件的邮件。'
msg.attach(MIMEText(body, 'plain'))
# 添加附件
attachment = MIMEBase('application', 'octet-stream')
with open('example.txt', 'rb') as f:
attachment.set_payload(f.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f"attachment; filename={'example.txt'}")
msg.attach(attachment)
# 发送邮件
smtp_obj = smtplib.SMTP('smtp.example.com', 587)
smtp_obj.starttls()
smtp_obj.login('username', 'password')
smtp_obj.sendmail(from_addr, to_addr, msg.as_string())
smtp_obj.quit()
javax.mail
库发送附件。以下是一个简单的示例:import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class SendEmailWithAttachment {
public static void main(String[] args) {
String to = "recipient@example.com";
String from = "sender@example.com";
String host = "smtp.example.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", "587");
Session session = Session.getInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("带附件的邮件");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setText("这是一个带附件的邮件。");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
mimeBodyPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("example.txt") {
@Override
public String getContentType() {
return "application/octet-stream";
}
};
mimeBodyPart.setDataHandler(new DataHandler(fileDataSource));
mimeBodyPart.setFileName("example.txt");
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
请注意,这些示例仅用于演示目的,实际应用中需要根据具体需求进行修改和调整。同时,您需要使用自己的SMTP服务器和凭据来发送邮件。
领取专属 10元无门槛券
手把手带您无忧上云