如何发送我的System.out.println();作为电子邮件



我有一个程序,可以在控制台上打印输出,这个程序读取excel文件中的内容,并在控制台上输出excel电子表格中的所有内容。我已经可以通过我的电子邮件类发送普通文本,但我正试图通过电子邮件在控制台上发送excel文件的输出,这是我的代码,其中有一些描述:

public class Sendexcelcontent {
private static final String NAME = "C:\Users\..........\excelfile.xlsx";
public static void excelfilereader() {
try {
FileInputStream file = new FileInputStream(new File(NAME));
Workbook workbook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Sheet> sheets = workbook.sheetIterator();
while (sheets.hasNext()) {
Sheet sh = sheets.next();
System.out.println("Sheet name is " + sh.getSheetName());
System.out.println("---------");
processLines(dataFormatter, sh);
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void processLines(DataFormatter dataFormatter, Sheet sh) {
boolean printLine = false;
Iterator<Row> iterator = sh.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();

Iterator<Cell> cellIterator = row.iterator();
Cell cell = cellIterator.next();
String text = dataFormatter.formatCellValue(cell);
}
}

private static void printRow(DataFormatter dataFormatter, Row row) {
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "t");
}
System.out.println();
}

public static void sendemail() {
//authentication info
final String username = "...";
final String password = "...";
String fromEmail = "...";
String toEmail = "...";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "false");
properties.put("mail.smtp.host", "...");
properties.put("mail.smtp.port", "...");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
//Start our mail message
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(fromEmail));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject("Subject Line");
msg.setText("NORMAL TEXT MESSAGE");

Transport.send(msg);
System.out.println("Message sent");
} catch (MessagingException e) {
e.printStackTrace();
}

}

}

您可以将System.out设置为指向StringWriter

通过这种方式,您可以获得字符串形式的输出,并将其写在电子邮件中:

StringWriter emailWriter=new StringWriter();
PrintWriter pw=new PrintWriter(emailWriter);
System.setOut(pw);
ReadInvoices.main(new String[0]);
String text=emailWriter.toString();
//...
msg.setText(text);

相关内容

最新更新