How do I send an e-mail in Java?

后端 未结 11 1578
一整个雨季
一整个雨季 2020-12-01 01:55

I need to send e-mails from a servlet running within Tomcat. I\'ll always send to the same recipient with the same subject, but with different contents.

What\'s a sim

11条回答
  •  佛祖请我去吃肉
    2020-12-01 02:49

    To followup on jon's reply, here's an example of sending a mail using simple-java-mail.

    The idea is that you don't need to know about all the technical (nested) parts that make up an email. In that sense it's a lot like Apache's commons-email, except that Simple Java Mail is a little bit more straightforward than Apache's mailing API when dealing with attachments and embedded images. Spring's mailing facility works as well but is a bit awkward in use (for example it requires an anonymous innerclass) and ofcourse you need to a dependency on Spring which gets you much more than just a simple mailing library, since it its base it was designed to be an IOC solution.

    Simple Java Mail btw is a wrapper around the JavaMail API.

    final Email email = new Email();
    
    email.setFromAddress("lollypop", "lolly.pop@somemail.com"); 
    email.setSubject("hey");
    email.addRecipient("C. Cane", "candycane@candyshop.org", RecipientType.TO);
    email.addRecipient("C. Bo", "chocobo@candyshop.org", RecipientType.BCC); 
    email.setText("We should meet up! ;)"); 
    email.setTextHTML("We should meet up!");
    
    // embed images and include downloadable attachments 
    email.addEmbeddedImage("wink1", imageByteArray, "image/png");
    email.addEmbeddedImage("wink2", imageDatesource); 
    email.addAttachment("invitation", pdfByteArray, "application/pdf");
    email.addAttachment("dresscode", odfDatasource);
    
    new Mailer("smtp.host.com", 25, "username", "password").sendMail(email);
    // or alternatively, pass in your own traditional MailSession object.
    new Mailer(preconfiguredMailSession).sendMail(email);
    
    • simple-java-mail
    • Apache Commons mail
    • Spring mail
    • JavaMail

提交回复
热议问题