Java 如何使用sendmail发送附件
我正在使用这个类发送邮件,它可以工作,但现在我想添加附件如何添加它,请帮助,如果你可以Java 如何使用sendmail发送附件,java,email,Java,Email,我正在使用这个类发送邮件,它可以工作,但现在我想添加附件如何添加它,请帮助,如果你可以 public static void sendMail(String subject, String body, String toEmail, String ccEmail, String fromMail) throws IOException { Random generator = new Random(); int r
public static void sendMail(String subject, String body, String toEmail, String ccEmail, String fromMail)
throws IOException {
Random generator = new Random();
int r = Math.abs(generator.nextInt());
body = body.replaceAll("(\\r|\\n)", "");
body = body.replaceAll("\"", "\\\\\"");
body = body.replaceAll("&", "\\\\&");
body = body.replaceAll("©", "\\\\©");
//body = body.replaceAll("> <", ">\\\n<");
if(CommonUtils.emptyString(fromMail))
fromMail = "No Reply <iotasol@pcc.com>";
else
fromMail = "No Reply <"+fromMail+">";
ProcessBuilder processBuilder = new ProcessBuilder(
ApplicationProperties.MAIL_SENDER_SH_PATH, CommonUtils.getEmptyStringForNull(subject), CommonUtils.getEmptyStringForNull(body),
toEmail, ccEmail, String.valueOf(r), fromMail);
processBuilder.start();
}
publicstaticvoidsendmail(stringsubject、stringbody、stringtoemail、stringccemail、stringfrommail)
抛出IOException{
随机生成器=新随机();
int r=Math.abs(generator.nextInt());
body=body.replaceAll(“(\\r |\\n)”,”;
body=body.replaceAll(“\”,“\”);
body=body.replaceAll(“&”、“\\\&”);
body=body.replaceAll(“”,“\\\&&169;”);
//body=body.replaceAll(“>\\\n作为一个想法,如果您需要发送图像:将其与base64内联
附件取决于所使用的库、所使用的邮件服务器等等。从您的代码示例中,我可以看出您正在使用外部邮件程序发送电子邮件。您可以创建一个ProcessBuilder并调用一个操作系统工具来发送电子邮件
MimeBodyPart messageBodyPart = new MimeBodyPart();
File file = new File("somefile.txt");
if (file.exists()) {
DataSource source = new FileDataSource("somefile.txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
我不会使用此解决方案。首先,它取决于操作系统(在windows上,您没有mail命令)。其次,这是没有效率的;因为您为此创建了外部进程(想象一下发送许多电子邮件)
相反,尝试使用java中现有的邮件解决方案(您将需要:mail.jar和activation.jar)。使用它,您可以直接从应用程序发送电子邮件,而不需要依赖外部工具
使用mailJava库,您可以做任何您想做的事情,您也可以查看。这是一个小型但方便的Java邮件库包装器,可以帮助您发送电子邮件和附件。如“使用fluent API发送电子邮件”一节所示,您可以执行以下操作:
Email email = Email.create()
.from("from@foo.org")
.to("to@bar.com")
.subject("test")
.addText("Hello!")
.addHtml(
"<html><body><h1>Hey!</h1>" +
"<img src='cid:c.png'><h2>Hay!</h2></body></html>")
.embed(attachment().bytes(new File("d:\\c.png")))
.attach(attachment().file("d:\\b.jpg"));
Email-Email=Email.create()
.来自(”from@foo.org")
.至(”to@bar.com")
.受试者(“测试”)
.addText(“你好!”)
.addHtml(
“嘿!”+
“嘿!”)
.embed(附件().bytes(新文件(“d:\\c.png”))
.attach(附件().file(“d:\\b.jpg”);
在本例中,您可以看到两种附加文件的方法:嵌入文件以使其显示在HTML内容中,或普通附加。当然,您不必使用fluent界面,这只是此库的一个选项