发送电子邮件Java - 教程问题

时间:2011-09-09 18:03:38

标签: java properties javamail

trying this example使用java发送电子邮件。

我需要知道代码在哪里使用属性文件的属性。 (如例所示)?并且,在代码中被引用的地方?

注意: 此外,我应该在属性文件中替换的值是什么,如果我要使用Google SMTP?

            import java.util.*;
            import java.io.*;
            import javax.mail.*;
            import javax.mail.internet.*;

             /**
            * Simple demonstration of using the javax.mail API.
            *
        * Run from the command line. Please edit the implementation
        * to use correct email addresses and host name.
        */
        public final class Emailer {

          public static void main( String... aArguments ){
            Emailer emailer = new Emailer();
            //the domains of these email addresses should be valid,
            //or the example will fail:
            emailer.sendEmail(
              "fromblah@blah.com", "toblah@blah.com",
               "Testing 1-2-3", "blah blah blah"
            );
           }

          /**
          * Send a single email.
          */
          public void sendEmail(
            String aFromEmailAddr, String aToEmailAddr,
            String aSubject, String aBody
          ){
            //Here, no Authenticator argument is used (it is null).
            //Authenticators are used to prompt the user for user
            //name and password.
            Session session = Session.getDefaultInstance( fMailServerConfig, null );
            MimeMessage message = new MimeMessage( session );
            try {
              //the "from" address may be set in code, or set in the
              //config file under "mail.from" ; here, the latter style is used
              //message.setFrom( new InternetAddress(aFromEmailAddr) );
              message.addRecipient(
                Message.RecipientType.TO, new InternetAddress(aToEmailAddr)
              );
              message.setSubject( aSubject );
              message.setText( aBody );
              Transport.send( message );
            }
            catch (MessagingException ex){
              System.err.println("Cannot send email. " + ex);
            }
          }

          /**
          * Allows the config to be refreshed at runtime, instead of
          * requiring a restart.
          */
          public static void refreshConfig() {
            fMailServerConfig.clear();
            fetchConfig();
          }

          // PRIVATE //

          private static Properties fMailServerConfig = new Properties();

          static {
            fetchConfig();
          }

          /**
          * Open a specific text file containing mail server
          * parameters, and populate a corresponding Properties object.
          */
          private static void fetchConfig() {
            InputStream input = null;
            try {
              //If possible, one should try to avoid hard-coding a path in this
              //manner; in a web application, one should place such a file in
              //WEB-INF, and access it using ServletContext.getResourceAsStream.
              //Another alternative is Class.getResourceAsStream.
              //This file contains the javax.mail config properties mentioned above.
              input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );
              fMailServerConfig.load( input );
            }
            catch ( IOException ex ){
              System.err.println("Cannot open and load mail server properties file.");
            }
            finally {
              try {
                if ( input != null ) input.close();
              }
              catch ( IOException ex ){
                System.err.println( "Cannot close mail server properties file." );
              }
            }
          }
        } 

4 个答案:

答案 0 :(得分:0)

首次加载类时,static initializer block内的代码已执行。

static {
   fetchConfig();
}

您会看到调用fetchConfig()方法然后加载fMailServerConfig属性。

private static Properties fMailServerConfig = new Properties();

private static void fetchConfig() {
   // ...[omitted stuff]...
   input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );
   fMailServerConfig.load( input );
   // ...[omitted stuff]...
}

请注意fetchConfig()方法是static - 它是从静态初始化程序调用的,所以它需要是静态的,因为还没有真正的类实例。此外,我们可能对所有实例使用相同的配置,因此不需要每个实例都有自己的配置。

另请注意,该方法为private,因为我们不希望从其他任何位置调用该方法。

javax.mail包将知道要使用的属性。即,mail.hostmail.from等(javax.mail documentation here

关于使用Google Gmail for SMTP的说明

出于安全考虑,使用Google的SMTP服务器可能会有点棘手。谷歌如何知道你不仅仅是一些使用它们作为中继的垃圾邮件发送者?您可能需要先与他们进行身份验证 - 他们有example code for using Google Gmail APIs您可以阅读和使用,但这超出了我的javax.mail内容。

答案 1 :(得分:0)

  private static void fetchConfig() {

打开一个FileInputStream,将数据加载到fMailServerConfig,定义为:

  private static Properties fMailServerConfig = new Properties();

属性类负责阅读此内容。它使用以下代码生成一条消息:

  Session session = Session.getDefaultInstance( fMailServerConfig, null );
  MimeMessage message = new MimeMessage( session );

关于Properties的细节,我不能说目的是什么。也许为该示例提供了更多代码。 Properties是一个Java框架类吗?

答案 2 :(得分:0)

fetchConfig()中调整此行以加载您的设置:

input = new FileInputStream( "C:\\Temp\\MyMailServer.txt" );

对于第二个问题,请阅读此google configuration web page ...

这些方面的东西对我有用:

mail.transport.protocol   = smtps
mail.smtp.starttls.enable = true
mail.smtps.port           = 465
mail.smtps.host           = smtp.gmail.com
mail.smtps.auth           = true

答案 3 :(得分:0)

您可以在没有属性文件的情况下使用它。我的下面代码非常完美。使用它

只需调用此函数即可向客户端发送自动电子邮件。 参数“to”是您要向其发送电子邮件的电子邮件地址。

我通常在Maven项目中这样做。如果您正在使用maven项目,则导入以下依赖项。

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

要附加pdf,请参阅 https://www.tutorialspoint.com/java/java_sending_email.htm

private void sendMail(String to, String subject, String emailBody) throws MessagingException{
    final String username = "youremail@gmail.com";
    final String password = "emailPassword";

    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("shubham20.yeole@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
        message.setSubject(subject);
        message.setContent(emailBody, "text/html; charset=utf-8");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
相关问题