【问题标题】:Send email to arraylist retrieved from database将电子邮件发送到从数据库中检索到的数组列表
【发布时间】:2016-07-20 11:31:19
【问题描述】:

我正在从事一个项目,我需要从数据库中检索电子邮件地址,然后向他们发送电子邮件。我已经在arraylist 中检索了这些电子邮件地址。像这样:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javaapplication1.Person;

public class ABC {
    public static void main(String[] args) throws SQLException {
        ArrayList<Person> personlist = new ArrayList<Person>();
        //List<Person> personlist = new List<Person>();
        try {


            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","gsjsc","gsjschanna");
            Statement st=con.createStatement();

            ResultSet srs = st.executeQuery("SELECT * FROM person2");
            while (srs.next()) {
                Person person = new Person();
                person.setName(srs.getString("name"));
                person.setJobtitle(srs.getString("jobtitle"));
               // person.setFrequentflyer(srs.getInt("frequentflyer"));
                personlist.add(person);
            }

            System.out.println(personlist.size());
            for (int a=0;a<personlist.size();a++)
            {
            System.out.println(personlist.get(a).getName());
            System.out.println(personlist.get(a).getJobtitle());
            // System.out.println(personlist.get(2).getName());
            // System.out.println(personlist.get(3).getName());
            }
            //System.out.println(personlist.get(4));

        //System.out.println(namelist.);
        } catch (Exception e) {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }
    }
}

Person.java:包含所有的 setter 和 getter。

编辑

现在我必须向对象人员的数组列表中检索到的那些电子邮件地址发送电子邮件。 我有一个代码用于向数组列表中的多个收件人发送电子邮件,如下所示:

    package javaapplication1;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailToGroupDemo {

 public static void main(String[] args) {

  // Create a SendEmail object and call start 
  // method to send a mail in Java.
  SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
  sendEmailToGroup.start();

 }

 private void start() {

  // For establishment of email client with 
  // Google's gmail use below properties.
  // For TLS Connection use below properties
  // Create a Properties object 
  Properties props = new Properties();

  // these properties are required
  // providing smtp auth property to true
  props.put("mail.smtp.auth", "true");
  // providing tls enability
  props.put("mail.smtp.starttls.enable", "true");
  // providing the smtp host i.e gmail.com
  props.put("mail.smtp.host", "smtp.gmail.com");
  // providing smtp port as 587
  props.put("mail.smtp.port", "587");

  // For SSL Connection use below properties

  /*props.put("mail.smtp.host", "smtp.gmail.com");
   props.put("mail.smtp.socketFactory.port", "465");
   props.put("mail.smtp.socketFactory.class",
     "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.port", "465");*/

  // Create Scanner object to take necessary 
  // values from the user.
  Scanner scanner = new Scanner(System.in);

  System.out.println("Please provide your Username for Authentication ...");
  final String Username = scanner.next();

  System.out.println("Please provide your Password for Authentication ...");
  final String Password = scanner.next();

  System.out.println("Please provide Email Address from which you want to send Email ...");
  final String fromEmailAddress = scanner.next();

  System.out.println("Please provide Email Addresses to which you want to send Email ...");
  System.out.println("If you are done type : Done or done");

  // ArrayLists to store email addresses entered by user
  ArrayList< String> emails = (ArrayList< String >) getEmails();

  System.out.println("Please provide Subject for your Email ... ");
  final String subject = scanner.next();

  System.out.println("Please provide Text Message for your Email ... ");
  final String textMessage = scanner.next();

  // Create a Session object based on the properties and 
  // Authenticator object
  Session session = Session.getDefaultInstance(props, 
    new LoginAuthenticator(Username,Password));

  try {

   // Create a Message object using the session created above
   Message message = new MimeMessage(session);

   // setting email address to Message from where message is being sent
   message.setFrom(new InternetAddress(fromEmailAddress));

   // setting the email addressess to which user wants to send message 
   message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails));

   // setting the subject for the email 
   message.setSubject(subject);

   // setting the text message which user wants to send to recipients
   message.setText(textMessage);

   // Using the Transport class send() method to send message 
   Transport.send(message);

   System.out.println("\nYour Message delivered successfully ....");

  } catch (MessagingException e) {

   throw new RuntimeException(e);

  }  
 }

 // This method takes a list of email addresses and 
 // returns back an array of Address by looping the 
 // list one by one and storing it into Address[]
 private Address[] getEmailsList(ArrayList< String > emails) {

  Address[] emaiAddresses = new Address[emails.size()];

  for (int i =0;i < emails.size();i++) {
   try {
    emaiAddresses[i] = new InternetAddress(emails.get(i));
   }
   catch (AddressException e) {

    e.printStackTrace();
   }
  }
  return emaiAddresses;
 }

 // This method prompts user for email group to which he
 // wants to send message
 public List< String > getEmails() {
  ArrayList< String > emails = new ArrayList< String >();

  int counter = 1;
  String address = "";
  Scanner scanner = new Scanner(System.in);

  // looping inifinitely times as long as user enters 
  // emails one by one
  // the while loop breaks when user types done and 
  // press enter.
  while(true) {

   System.out.println("Enter E-Mail : " + counter);
   address = scanner.next();

   if(address.equalsIgnoreCase("Done")){
    break;
   }
   else {
    emails.add(address);
    counter++;
   }
  }

  return emails;
 }
}

// Creating a class for Username and Password authentication
// provided by the user.
class LoginAuthenticator extends Authenticator {
 PasswordAuthentication authentication = null;

 public LoginAuthenticator(String username, String password) {
  authentication = new PasswordAuthentication(username,password);
 }

 @Override
 protected PasswordAuthentication getPasswordAuthentication() {
  return authentication;
 }
}     

这是一个完全不同的代码。但是可以向一群人发送电子邮件。但问题是我们必须手动输入电子邮件地址。而我想将邮件发送到从 ABC 类检索到的地址。有人可以给我一个集成代码(对于两个类),那就太好了。

【问题讨论】:

  • 注意:请提供完整的工作代码,截止日期已近。 - 哈哈,祝你好运
  • 您的问题和您的代码不匹配。在 Person 对象中设置的电子邮件在哪里?您的另一段代码从控制台获取电子邮件列表,并且似乎与人员列表获取代码没有任何联系。
  • Please answer with a full working code, deadline is close - 我通常会编辑这种垃圾,但在你的情况下,我会把它留在里面,这样每个人都可以看到它。它赤裸的脸颊……read this.
  • halfer ,好的,删除它,感谢您对新手如此粗鲁。但是我的目标不是要优先于任何人,而是要获得完整的工作代码,因为我已经筋疲力尽了,而且我看到有些人发布了我觉得难以理解的不完整代码
  • 不,粗鲁是你的——这正是我要表达的意思。一旦您阅读了我提供的链接,您就会明白这一点。你现在不知道如何对待志愿者,但我希望你能学到!

标签: java sql-server email arraylist


【解决方案1】:

这应该将PersonPersonArrayListString 转换为来自所有人的电子邮件。

public ArrayList<String> getEmailsFromPersons(List<Person> persons) {
    ArrayList<String> emails = new ArrayList<String>();
    for(Person person : persons) {
        String email = person.getEmail();
        if(email != null && !email.trim().isEmpty()) {
            emails.add(email);
        }
    }
    return emails;
}

【讨论】:

    【解决方案2】:

    我已在 arraylist 中检索到这些电子邮件地址。像这样:

    我没有看到 Person 对象中设置了任何电子邮件。但是仍然会尝试根据您编辑后的理解来回答您的问题。下面的代码应该适合您的需要(请不要介意任何错误,因为我是在没有任何检查的情况下即时编写的):

    public class ABC {
    public static void main(String[] args) throws SQLException {
        ArrayList<Person> personlist = new ArrayList<Person>();
        // Creating a separate list of emails for Persons
        List<String> personEmails = new ArrayList<String>();
    
        //List<Person> personlist = new List<Person>();
        try {
    
    
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","gsjsc","gsjschanna");
            Statement st=con.createStatement();
    
            ResultSet srs = st.executeQuery("SELECT * FROM person2");
            String email = "";
            while (srs.next()) {
                Person person = new Person();
                person.setName(srs.getString("name"));
                person.setJobtitle(srs.getString("jobtitle"));
                // person.setFrequentflyer(srs.getInt("frequentflyer"));
                // I am assuming you would be setting email in person like this
                email = srs.getString("email");
                person.setEmail(email);
                // Add the email simultaneously to the separate list
                personEmails.add(email);
                personlist.add(person);
            }
    
            System.out.println(personlist.size());
            for (int a=0;a<personlist.size();a++)
            {
            System.out.println(personlist.get(a).getName());
            System.out.println(personlist.get(a).getJobtitle());
            // System.out.println(personlist.get(2).getName());
            // System.out.println(personlist.get(3).getName());
            }
            //System.out.println(personlist.get(4));
    
        //System.out.println(namelist.);
        } catch (Exception e) {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }
    
    
        // call the email sender method of yours with the newly created list
        SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
        // Obviously, make that start() method public having parameter of type List<String> instead of calling getEmails() within it
        sendEmailToGroup.start(personEmails); 
        // Very little remains to be done, I hope you can figure it out easily
    } 
    }
    

    【讨论】:

    • 谢谢你。你提到的一切,但在 `message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails));` 中出现错误,因为电子邮件无法解决。如果您可以发布完整的工作代码,将会很有帮助
    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多