以下代码供您参考。在Java中将Pojo转换为MimeMessage 试图使用Javax Mail发送电子邮件使用了以下代码,它没有将InputStream转换为MimeMessage。所有Mimemessage属性均为空。
public class MailMessage
{
private String fromName;
private String fromAddress;
private String subject;
private String body;
private boolean attachment;
private String attachmentName;
private String attachmentContent;
private String attachmentType;
private List<MailRecipient> mailRecipients;
}
public class sentEmail
{
public static void main(String args[])
{
MailMessage MailMessage = new new MailMessage();
List<MailRecipient> mailRecipients = new ArrayList<MailRecipient>();
MailRecipient mailRecipient = new MailRecipient();
MailRecipientType mailRecipientType = new MailRecipientType();
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
mailMessage.setFromName("Sender Name");
mailMessage.setFromAddress("xxx@gmail.com");
mailMessage.setSubject("Maile Subject");
mailMessage.setBody(rs.getString("Hi This is testing email"));
mailRecipient.setName("Recipient_name");
mailRecipient.setAddress("yyyy@gmail.com");
mailRecipientType.setName("TO");
mailRecipients.add(mailRecipient);
mailMessage.setMailRecipients(mailRecipients);
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(mailMessage);
oos.flush();
bytes = bos.toByteArray();
javax.mail.Session session =javax.mail.Session.getDefaultInstance(props);
InputStream str = new ByteArrayInputStream(bytes);
Transport transport = session.getTransport();
MimeMessage msg = new MimeMessage(session, str);
transport.connect("url", "userName", "Password");
transport.sendMessage(msg, msg.getAllRecipients());
}
我正在使用以下代码。
答案 0 :(得分:0)
更改
MailMessage MailMessage = new new MailMessage();
到
MailMessage mailMessage = new new MailMessage(); // object name start with small m because you are using it onward.
为什么不直接在MimeMessage
中设置参数?像
MimeMessage message= new MimeMessage(session);
message.setFrom("Sender Name");
message.setFrom("xxx@gmail.com");
message.setSubject("Maile Subject");
message.setContent(rs.getString("Hi This is testing email"));
//Rest of your code
// and send