How do I send an e-mail in Java?

后端 未结 11 1588
一整个雨季
一整个雨季 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条回答
  •  猫巷女王i
    2020-12-01 02:40

    Add java.mail jar into your class path if it is non maven project Add the below dependency into your pom.xml execute the code

     
            javax.mail
            mail
            1.4
        
    

    Below is the tested code

    import java.util.Date;
        import java.util.Properties;
    
        import javax.mail.Authenticator;
        import javax.mail.Message;
        import javax.mail.PasswordAuthentication;
        import javax.mail.Session;
        import javax.mail.Transport;
        import javax.mail.internet.InternetAddress;
        import javax.mail.internet.MimeMessage;
    
        public class MailSendingDemo {
            static Properties properties = new Properties();
            static {
                properties.put("mail.smtp.host", "smtp.gmail.com");
                properties.put("mail.smtp.port", "587");
                properties.put("mail.smtp.auth", "true");
                properties.put("mail.smtp.starttls.enable", "true");
            }
            public static void main(String[] args) {
                String returnStatement = null;
                try {
                    Authenticator auth = new Authenticator() {
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication("yourEmailId", "password");
                        }
                    };
                    Session session = Session.getInstance(properties, auth);
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress("yourEmailId"));            
                    message.setRecipient(Message.RecipientType.TO, new InternetAddress("recepeientMailId"));
                    message.setSentDate(new Date());
                    message.setSubject("Test Mail");
                    message.setText("Hi");
                    returnStatement = "The e-mail was sent successfully";
                    System.out.println(returnStatement);    
                    Transport.send(message);
                } catch (Exception e) {
                    returnStatement = "error in sending mail";
                    e.printStackTrace();
                }
            }
        }
    

提交回复
热议问题