我有以下程序,它完美无缺,并通过java邮件发送邮件api我在下面的程序中唯一的问题是在邮件正文中没有文本,但是在下面的程序中你可以看到我已将正文输入为“邮件正文的测试邮件”,请告知我在下面的程序中需要做哪些更改,以便在邮件正文中我也可以获取文本。
根据人们的建议,我更新了下面的代码,
public class abcMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdg@abc.com";
//String mailCc = "avdg@abc.com ";
String mailFrom = "avdg@abc.com";
String mailSubject = "sgdtetrtrr";
String mailText = "Test Mail for mail body ";
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(true);
//creating the message
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Address[] cc = new Address[] {
new InternetAddress("avdg@abc.com"),
new InternetAddress("saxenasaral@gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\SettingupRulesin outlook2003.pdf";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您的错误可能是您要分配的 messageBodyPart = new MimeBodyPart(); 然后 messageBodyPart = new MimeMultipart(); 之后,在将其添加到emailMessage之前,请清除您添加的邮件正文。