forked from mthli/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailTest.java
More file actions
59 lines (53 loc) · 1.69 KB
/
MailTest.java
File metadata and controls
59 lines (53 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package mail;
import java.io.*;
import java.nio.charset.*;
import java.nio.file.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;
/**
* This program shows how to use JavaMail to send mail messages.
* @author Cay Horstmann
* @version 1.00 2012-06-04
*/
public class MailTest
{
public static void main(String[] args) throws MessagingException, IOException
{
Properties props = new Properties();
try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties")))
{
props.load(in);
}
List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));
String from = lines.get(0);
String to = lines.get(1);
String subject = lines.get(2);
StringBuilder builder = new StringBuilder();
for (int i = 3; i < lines.size(); i++)
{
builder.append(lines.get(i));
builder.append("\n");
}
Console console = System.console();
String password = new String(console.readPassword("Password: "));
Session mailSession = Session.getDefaultInstance(props);
// mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(builder.toString());
Transport tr = mailSession.getTransport();
try
{
tr.connect(null, password);
tr.sendMessage(message, message.getAllRecipients());
}
finally
{
tr.close();
}
}
}