sending mail from apache tomcat

后端 未结 3 575
梦毁少年i
梦毁少年i 2021-01-05 07:35

I am working on a web project using Tomcat 6 as my webserver and JSP as frontend. I want to send a mail from the web server to an email account. How can I achieve this?

3条回答
  •  无人及你
    2021-01-05 07:58

    This works fine (gmail example) :

    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class SendMail {
    
        public static void main(String[] args) {
    
            final String username = "your_usename_goes_here";
            final String password = "your_password_goes_here";
    
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
    
            Session session = Session.getInstance(props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
              });
    
            try {
    
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("fromSomeone@gmail.com"));
                message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("toSomeone@gmail.com"));
                message.setSubject("A testing mail header !!!");
                message.setText("Dear Mail Crawler,"
                    + "\n\n No spam to my email, please!");
    
                Transport.send(message);
    
                System.out.println("Done");
    
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

提交回复
热议问题