【发布时间】:2015-07-17 00:22:05
【问题描述】:
我正在处理我的项目,我想在 Java 应用程序中从我的数据库中发送电子邮件。我已经与我的数据库建立了连接,我从中提取电子邮件、主题、正文和附件。我还创建了发送与电子邮件服务器连接的电子邮件的代码。我想要将这两个代码组合在一起,我希望数据库中的信息填充到我的发送电子邮件代码中。这是我用 Java 连接数据库的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connect {
public static void main(String[] args) {
Connection conn = null;
String dbName = "Employee";
String serverip="100.00.000.000";
String serverport="3316";
String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
Statement stmt = null;
ResultSet result = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String databaseUserName = "sys";
String databasePassword = "123";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
stmt = conn.createStatement();
result = null;
String emailTo,emailSubject,emailBody,emailAttachments;
result = stmt.executeQuery("Select * From Employees");
while (result.next()) {
emailTo =result.getString("emailTo");
emailSubject = result.getString("emailSubject");
emailBody = result.getString("emailBody");
emailAttachments = result.getString("emailAttachments");
System.out.println(emailTo + " /" + emailSubject + " /" + emailBody + " /" + emailAttachments);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我发送电子邮件的代码:
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 Send {
public static void main(String[] args) {
final String username = "work@gmail.com";
final String password = "1234";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.00.000.000");
props.put("mail.smtp.port", "20");
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("work@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("Here I want to use emailTo from my Database"));
message.setSubject("Here emailSubject");
message.setText("Here emailBody");
message.setAttachment("Here emailAttachments");
Transport.send(message);
System.out.println("Success");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
如果有人可以帮助结合这个,请告诉我。提前致谢。
【问题讨论】:
-
尝试从OOP 的角度思考,而不是将所有程序代码集中到
main方法中。 -
使用更多方法,以便您更轻松地跟踪您的代码