【问题标题】:How do I send an e-mail in Java?如何在 Java 中发送电子邮件?
【发布时间】:2010-10-27 11:06:57
【问题描述】:

我需要从运行在 Tomcat 中的 servlet 发送电子邮件。我将始终以相同的主题发送给同一收件人,但内容不同。

用 Java 发送电子邮件的简单易行的方法是什么?

相关:

How do you send email from a Java app using GMail?

【问题讨论】:

标签: java email tomcat servlets


【解决方案1】:

这是我的代码:

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.
}

您可以在此处从 Sun 获取 JavaMail 库:http://java.sun.com/products/javamail/

【讨论】:

  • 如何发送多部分消息,以便可以呈现 HTML 的客户端呈现它?
  • @Esteban:在此处查看 Sun 的教程:java.sun.com/developer/EJTechTips/2004/tt0426.html
  • 我也在做同样的事情,但有例外:Could not connect to SMTP host: smtp.myisp.com, port: 25 它如何发送电子邮件而不询问“发件人”ID 的密码?
【解决方案2】:

JavaMail 使用起来可能有点麻烦。如果您想要一个更简单、更清洁的解决方案,请查看 JavaMail 的 Spring 包装器。参考文档在这里:

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

但是,这确实意味着您的应用程序中需要 Spring,如果这不是一个选项,那么您可以查看另一个开源包装器,例如 simple-java-mail:

simplejavamail.org

或者,您可以直接使用 JavaMail,但上述两种解决方案是使用 Java 发送电子邮件的更简单、更简洁的方式。

【讨论】:

【解决方案3】:

另一个包装 Java Mail API 的选项是 Apache's commons-email

来自他们的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();

【讨论】:

  • 这个库是有限的,没有通过 imap 接收电子邮件的文档。我最终不得不使用功能和文档更丰富的 Java Mail API。
  • @JohnMerlino 我相信 Apache 库仅用于发送电子邮件,而不是接收它;而IMAP只和后者有关。
  • Apache commons-email 试图简化电子邮件 API,但它遗漏了一些明显的简化。 Simple Java Mail 很重要,而且还有更多功能。它与 Apache commons-email 一样是开源的。
【解决方案4】:

为了跟进 jon 的回复,这里有一个使用 simple-java-mail 发送邮件的示例。

这个想法是您不需要了解构成电子邮件的所有技术(嵌套)部分。从这个意义上说,它很像 Apache 的 commons-email,除了 Simple Java Mail 在处理附件和嵌入图像时比 Apache 的邮件 API 更简单一点。 Spring 的邮件功能也可以工作,但使用起来有点尴尬(例如,它需要一个匿名内部类),当然你需要依赖于 Spring,它不仅仅是一个简单的邮件库,因为它是设计的基础成为 IOC 解决方案。

Simple Java Mail btw 是 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);

【讨论】:

    【解决方案5】:

    我通常在 tomcat 的 server.xml 文件的 GlobalNamingResources 部分中定义我的 javamail 会话,以便我的代码不依赖于配置参数:

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

    我通过 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);
    

    【讨论】:

      【解决方案6】:

      如果您可以依赖外部 SMTP 服务器,JavaMail 就很棒。但是,如果您必须是自己的 SMTP 服务器,请查看 Asprin

      【讨论】:

        【解决方案7】:

        使用 Java 邮件库

        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();
        

        这是我用来让应用程序发送电子邮件的代码的截断版本。显然,在发送之前将正文和收件人放入邮件中可能会更适合您。

        maven 仓库位置是 artifactId: javax.mail, groupId: mail。

        【讨论】:

          【解决方案8】:

          如果是非 maven 项目,请将 java.mail jar 添加到您的类路径中 将以下依赖项添加到您的 pom.xml 中执行代码

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

          下面是测试代码

          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();
                      }
                  }
              }
          

          【讨论】:

            【解决方案9】:

            测试代码发送带有附件的邮件:

              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);
                }
            
            }
            

            【讨论】:

              【解决方案10】:

              这是简单的解决方案

              下载这些罐子: 1.Java邮箱 2. smtp 3.Java.mail

              [http://javapapers.com/core-java/java-email/][1]复制并粘贴以下代码

              编辑收件人邮箱、用户名和密码(Gmail 用户 ID 和密码)

              【讨论】:

                【解决方案11】:
                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
                

                【讨论】:

                • 欢迎来到 StackOverflow!虽然您发布的代码可能很好地满足了原始问题的要求,但尚不清楚您的贡献如何带来新的或与该问题的其他答案不同的东西。您应该提供一些额外的解释,说明您的回答与此问题的不同/优于公认的答案/其他高度投票的答案。
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2012-04-17
                • 2023-04-10
                • 2018-05-10
                • 1970-01-01
                • 2016-03-16
                • 2023-03-27
                相关资源
                最近更新 更多