How do I send an e-mail in Java?

后端 未结 11 1466
一整个雨季
一整个雨季 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("<img src='cid:wink1'><b>We should meet up!</b><img src='cid:wink2'>");
    
    // 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
    0 讨论(0)
  • 2020-12-01 02:50

    Yet another option that wraps the Java Mail API is Apache's commons-email.

    From their User Guide.

    SimpleEmail email = new SimpleEmail();
    email.setHostName("mail.myserver.com");
    email.addTo("jdoe@somewhere.org", "John Doe");
    email.setFrom("me@apache.org", "Me");
    email.setSubject("Test message");
    email.setMsg("This is a simple test of commons-email");
    email.send();
    
    0 讨论(0)
  • 2020-12-01 02:50

    Tested Code send Mail with attachment :

      public class SendMailNotificationWithAttachment {
    
                public static void mailToSendWithAttachment(String messageTosend, String snapShotFile) {
    
                    String to = Constants.MailTo;
                    String from = Constants.MailFrom;
                    String host = Constants.smtpHost;// or IP address
                    String subject = Constants.subject;
                    // Get the session object
                    Properties properties = System.getProperties();
                    properties.setProperty("mail.smtp.host", host);
                    Session session = Session.getDefaultInstance(properties);
                    try {
                        MimeMessage message = new MimeMessage(session);
                        message.setFrom(new InternetAddress(from));
                        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                        message.setSubject(subject);
                        // message.setText(messageTosend);
                        BodyPart messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setText(messageTosend);
                        Multipart multipart = new MimeMultipart();
                        multipart.addBodyPart(messageBodyPart);
    
                        messageBodyPart = new MimeBodyPart();
                        String filepath = snapShotFile;
    
                        DataSource source = new FileDataSource(filepath);
                        messageBodyPart.setDataHandler(new DataHandler(source));
    
                        Path p = Paths.get(filepath);
                        String NameOffile = p.getFileName().toString();
    
                        messageBodyPart.setFileName(NameOffile);
                        multipart.addBodyPart(messageBodyPart);
    
                        // Send the complete message parts
                        message.setContent(multipart);
    
                        // Send message
                        Transport.send(message);
    
            //          Log.info("Message is sent Successfully");
            //          System.out.println("Message is sent Successfully");
                        System.out.println("Message is sent Successfully");
        } catch (MessagingException e) {
        //          Log.error("Mail sending is Failed " + "due to" + e);
                    SendMailNotificationWithAttachment smnwa = new SendMailNotificationWithAttachment();
                    smnwa.mailSendFailed(e);
                    throw new RuntimeException(e);
                }
            }
    public void mailSendFailed(MessagingException e) {
            System.out.println("Mail sending is Failed " + "due to" + e);
            Log log = new Log();
            log.writeIntoLog("Mail sending is Failed " + "due to" + e.toString(), false);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 02:55

    use the Java Mail library

    import javax.mail.*
    
    ...
    
    Session mSession = Session.getDefaultInstance(new Properties());
    Transport mTransport = null;
    mTransport = mSession.getTransport("smtp");
    mTransport.connect(cServer, cUser, cPass);
    MimeMessage mMessage = new MimeMessage(mSession);
    mTransport.sendMessage(mMessage,  mMessage.getAllRecipients());
    mTransport.close();
    

    This is a truncated version of the code I use to have an application send emails. Obviously, putting a body and recipients in the message before sending it is probably going to suit you better.

    The maven repository location is artifactId: javax.mail, groupId: mail.

    0 讨论(0)
  • 2020-12-01 02:57

    Here's my code for doing that:

    import javax.mail.*;
    import javax.mail.internet.*;
    
    // Set up the SMTP server.
    java.util.Properties props = new java.util.Properties();
    props.put("mail.smtp.host", "smtp.myisp.com");
    Session session = Session.getDefaultInstance(props, null);
    
    // Construct the message
    String to = "you@you.com";
    String from = "me@me.com";
    String subject = "Hello";
    Message msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSubject(subject);
        msg.setText("Hi,\n\nHow are you?");
    
        // Send the message.
        Transport.send(msg);
    } catch (MessagingException e) {
        // Error.
    }
    

    You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

    0 讨论(0)
提交回复
热议问题