我有一个在应用程序启动时创建的文件列表,我希望这些文件通过电子邮件发送。电子邮件会发送,但他们没有任何附件。
以下是代码:
private Multipart getAttachments() throws FileNotFoundException, MessagingException
{
File folder = new File(System.getProperty("user.dir"));
File[] fileList = folder.listFiles();
Multipart mp = new MimeMultipart("mixed");
for (File file : fileList)
{
// ext is valid, and correctly detects these files.
if (file.isFile() && StringFormatter.getFileExtension(file.getName()).equals("xls"))
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(file, file.getName()));
messageBodyPart.setFileName(file.getName());
mp.addBodyPart(messageBodyPart);
}
}
return mp;
}
没有错误,警告或其他任何内容。我甚至尝试创建名为Multipart
的{{1}}并将其分配到childPart
到mp
,但这也无效。
我以这种方式分配附件:
.setParent()
如何通过Java正确发送多个附件?
答案 0 :(得分:1)
这是我自己的电子邮件实用程序类,请检查sendMail
方法是否适合您
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {
public enum SendMethod{
HTTP, TLS, SSL
}
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public static boolean isValidEmail(String address){
return (address!=null && address.matches(EMAIL_PATTERN));
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public static boolean sendEmail(final String recipients, final String from,
final String subject, final String contents,final String[] attachments,
final String smtpserver, final String username, final String password, final SendMethod method) {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpserver);
Session session = null;
switch (method){
case HTTP:
if (username!=null) props.setProperty("mail.user", username);
if (password!=null) props.setProperty("mail.password", password);
session = Session.getDefaultInstance(props);
break;
case TLS:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
case SSL:
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
}
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, recipients);
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(contents, "text/html");
multipart.addBodyPart(bodypart);
if (attachments!=null){
for (int co=0; co<attachments.length; co++){
bodypart = new MimeBodyPart();
File file = new File(attachments[co]);
DataSource datasource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(datasource));
bodypart.setFileName(file.getName());
multipart.addBodyPart(bodypart);
}
}
message.setContent(multipart);
Transport.send(message);
} catch(MessagingException e){
e.printStackTrace();
return false;
}
return true;
}
}
答案 1 :(得分:0)
您可以从所需的文件夹创建一个 zip 文件,然后将其作为普通文件发送。
public static void main(String[] args) throws IOException {
String to = "Your desired receiver email address ";
String from = "for example your GMAIL";
//Get the session object
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "Insert your password here");
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Write the subject");
String Final_ZIP = "C:\\Users\\Your Path\\Zipped.zip";
String FOLDER_TO_ZIP = "C:\\Users\\The folder path";
zip(FOLDER_TO_ZIP,Final_ZIP);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Write your text");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
DataSource source = new FileDataSource(Final_ZIP);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("ZippedFile.zip");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println(" Email has been sent successfully....");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
那么 Zip 函数是:
public static void zip( String srcPath, String zipFilePath) throws IOException {
Path zipFileCheck = Paths.get(zipFilePath);
if(Files.exists(zipFileCheck)) { // Attention here it is deleting the old file, if it already exists
Files.delete(zipFileCheck);
System.out.println("Deleted");
}
Path zipFile = Files.createFile(Paths.get(zipFilePath));
Path sourceDirPath = Paths.get(srcPath);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
Stream<Path> paths = Files.walk(sourceDirPath)) {
paths
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
try {
zipOutputStream.putNextEntry(zipEntry);
Files.copy(path, zipOutputStream);
zipOutputStream.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
System.out.println("Zip is created at : "+zipFile);
}