我正在尝试使用 Java 和 Gmail 发送电子邮件。我已将我的文件存储在云中,并将存储的文件作为附件发送到我的电子邮件。
它应该将这些文件添加到此邮件中,而不是这些文件的链接。
我怎样才能发送这样的附件?
我正在尝试使用 Java 和 Gmail 发送电子邮件。我已将我的文件存储在云中,并将存储的文件作为附件发送到我的电子邮件。
它应该将这些文件添加到此邮件中,而不是这些文件的链接。
我怎样才能发送这样的附件?
工作代码,我用过Java Mail 1.4.7 jar
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "your.mail.id@gmail.com";
final String password = "your.password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from.mail.id@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to.mail.id@gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
由于未知原因,当我向我的 gmail 地址发送电子邮件时,接受的答案部分有效。我有附件,但没有电子邮件的文本。
如果您想要附件和文本,请根据接受的答案尝试此操作:
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
更新 :
如果您想以 html 格式的内容发送邮件,您必须这样做
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
所以基本上setText
是用于原始文本,并且会很好地显示在包括 gmail 在内的每封服务器电子邮件上,setContent
更多的是用于 html 模板,如果您的内容被格式化为 html,它可能也适用于 gmail
使用 Spring Framework,您可以添加许多附件:
package com.mkyong.common;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailParseException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailMail
{
private JavaMailSender mailSender;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String dear, String content) {
MimeMessage message = mailSender.createMimeMessage();
try{
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource("/home/abdennour/Documents/cv.pdf");
helper.addAttachment(file.getFilename(), file);
}catch (MessagingException e) {
throw new MailParseException(e);
}
mailSender.send(message);
}
}
要了解如何配置您的项目来处理此代码,请完成阅读本教程。
这对我有用。
在这里,我假设我的附件是PDF
类型格式。
发表评论以清楚地理解它。
public class MailAttachmentTester {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "test@gmail.com";
// Sender's email ID needs to be mentioned
String from = "tester@gmail.com";
final String username = "tester@gmail.com";//change accordingly
final String password = "test";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
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));
// Set Subject: header field
message.setSubject("Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Please find the attachment below");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "D:/test.PDF";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Email Sent Successfully !!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
如果您允许,它也适用于 multi-attachments,即 NINCOMPOOP 的上述第一个答案,只需稍作修改,如下所示:
DataSource source,source2,source3,source4, ...;
source = new FileDataSource(myfile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(myfile);
multipart.addBodyPart(messageBodyPart);
source2 = new FileDataSource(myfile2);
messageBodyPart.setDataHandler(new DataHandler(source2));
messageBodyPart.setFileName(myfile2);
multipart.addBodyPart(messageBodyPart);
source3 = new FileDataSource(myfile3);
messageBodyPart.setDataHandler(new DataHandler(source3));
messageBodyPart.setFileName(myfile3);
multipart.addBodyPart(messageBodyPart);
source4 = new FileDataSource(myfile4);
messageBodyPart.setDataHandler(new DataHandler(source4));
messageBodyPart.setFileName(myfile4);
multipart.addBodyPart(messageBodyPart);
...
message.setContent(multipart);
要发送 html 文件,我在项目中使用了以下代码。
final String userID = "usermail@gmail.com";
final String userPass = "userpass";
final String emailTo = "mailto@gmail.com"
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
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 = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userID, userPass);
}
});
try {
Message message = new MimeMessage(session);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
message.setSubject("Hello, this is a test mail..");
Multipart multipart = new MimeMultipart();
String fileName = "fileName";
addAttachment(multipart, fileName);
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("No need to reply.");
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email successfully sent to: " + emailTo);
} catch (MessagingException e) {
e.printStackTrace();
}
private static void addAttachment(Multipart multipart, String fileName){
DataSource source = null;
File f = new File("filepath" +"/"+ fileName);
if(f.exists() && !f.isDirectory()) {
source = new FileDataSource("filepath" +"/"+ fileName);
BodyPart messageBodyPart = new MimeBodyPart();
try {
messageBodyPart.setHeader("Content-Type", "text/html");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}