How do I send an e-mail in Java?

后端 未结 11 1450
一整个雨季
一整个雨季 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:34

    Here is the simple Solution

    Download these jars: 1. Javamail 2. smtp 3. Java.mail

    Copy and paste the below code from [http://javapapers.com/core-java/java-email/][1]

    Edit the ToEmail, Username and Password (Gmail User ID and Pwd)

    0 讨论(0)
  • 2020-12-01 02:36
    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 sendMail {
    
        static  String  alertByEmail(String emailMessage){
            try{
                         
                final String fromEmail = "abc@gmail.com";
                final String password = "********"; //fromEmail password 
                final String toEmail = "xyz@gmail.com";
                System.out.println("Email configuration code start");
                Properties props = new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host set by default this
                props.put("mail.smtp.port", "587"); //TLS Port you can use 465 insted of 587
                props.put("mail.smtp.auth", "true"); //enable authentication
                props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
                //create Authenticator object to pass in Session.getInstance argument
                Authenticator auth = new Authenticator() 
                {
                
                    protected PasswordAuthentication getPasswordAuthentication() 
                    {
                            return new PasswordAuthentication(fromEmail, password);
                    }
                };
                            Session session = Session.getInstance(props, auth);
                
                            MimeMessage message = new MimeMessage(session);
                            message.setFrom(new InternetAddress(fromEmail));
                            message.addRecipient(Message.RecipientType.TO, new 
                                                                  InternetAddress(toEmail));
                            message.setSubject("ALERT");
                            message.setText(emailMessage);//here you can write a msg what you want to send... just remove String parameter in alertByEmail method oherwise call parameter
                            System.out.println("text:"+emailMessage);
                            Transport.send(message);//here mail sending process start.
                            System.out.println("Mail Sent Successfully");
            }
            catch(Exception ex)
            {
                            System.out.println("Mail fail");
                            System.out.println(ex);
            }
            return emailMessage;
            
            }
    public static void main(String[] args) {
        String emailMessage = "This mail is send using java code.Report as a spam";
        alertByEmail(emailMessage);
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    https://github.com/sumitfadale/java-important-codes/blob/main/Send%20a%20mail%20through%20java 
    
    
    enter code here
    
    0 讨论(0)
  • 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

     <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
    

    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();
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-01 02:45

    JavaMail can be a bit of a pain to use. If you want a simpler, cleaner, solution then have a look at the Spring wrapper for JavaMail. The reference docs are here:

    http://static.springframework.org/spring/docs/2.5.x/reference/mail.html

    However, this does mean you need Spring in your application, if that isn't an option then you could look at another opensource wrapper such as simple-java-mail:

    simplejavamail.org

    Alternatively, you can use JavaMail directly, but the two solutions above are easier and cleaner ways to send email in Java.

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

    JavaMail is great if you can rely on an outside SMTP server. If, however, you have to be your own SMTP server, then take a look at Asprin.

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

    I usually define my javamail session in the GlobalNamingResources section of tomcat's server.xml file so that my code does not depend on the configuration parameters:

    <GlobalNamingResources>
        <Resource name="mail/Mail" auth="Container" type="javax.mail.Session"
                  mail.smtp.host="localhost"/>
        ...
    </GlobalNamingResources>
    

    and I get the session via JNDI:

        Context context = new InitialContext();
        Session sess = (Session) context.lookup("java:comp/env/mail/Mail");
    
        MimeMessage message = new MimeMessage(sess);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject, "UTF-8");
        message.setText(content, "UTF-8");
        Transport.send(message);
    
    0 讨论(0)
提交回复
热议问题