|
| 1 | +import org.apache.commons.cli.*; |
| 2 | + |
| 3 | +import javax.mail.*; |
| 4 | +import javax.mail.internet.InternetAddress; |
| 5 | +import javax.mail.internet.MimeMessage; |
| 6 | +import java.util.Properties; |
| 7 | + |
| 8 | +public class Mail { |
| 9 | + public static void main(String[] args) throws MessagingException, ParseException { |
| 10 | + // --host=mail.test.com --port=25 [email protected] [email protected] |
| 11 | + CommandLineParser parser = new DefaultParser(); |
| 12 | + |
| 13 | + Options options = new Options(); |
| 14 | + options.addOption(Option.builder().longOpt("host") |
| 15 | + .desc("smtp server host") |
| 16 | + .hasArg() |
| 17 | + .build()); |
| 18 | + |
| 19 | + options.addOption(Option.builder().longOpt("port") |
| 20 | + .desc("smtp server port") |
| 21 | + .hasArg() |
| 22 | + .build()); |
| 23 | + |
| 24 | + options.addOption(Option.builder().longOpt("from") |
| 25 | + .desc("from address") |
| 26 | + .hasArg() |
| 27 | + .build()); |
| 28 | + |
| 29 | + options.addOption(Option.builder().longOpt("to") |
| 30 | + .desc("to address") |
| 31 | + .hasArg() |
| 32 | + .build()); |
| 33 | + |
| 34 | + CommandLine line = parser.parse(options, args); |
| 35 | + |
| 36 | + String host = line.getOptionValue("host"); |
| 37 | + String port = line.getOptionValue("port"); |
| 38 | + String from = line.getOptionValue("from"); |
| 39 | + String to = line.getOptionValue("to"); |
| 40 | + |
| 41 | + String subject = "test subject"; |
| 42 | + String body = "test message"; |
| 43 | + |
| 44 | + Properties props = System.getProperties(); |
| 45 | + props.put("mail.smtp.starttls.enable", true); |
| 46 | + props.put("mail.smtp.host", host); |
| 47 | + props.put("mail.smtp.port", port); |
| 48 | + props.put("mail.smtp.ssl.protocols", "SSLv2Hello SSLv3"); |
| 49 | + |
| 50 | + Session session = Session.getDefaultInstance(props, null); |
| 51 | + session.setDebug(true); |
| 52 | + |
| 53 | + MimeMessage message = new MimeMessage(session); |
| 54 | + message.setFrom(new InternetAddress(from)); |
| 55 | + |
| 56 | + InternetAddress toAddress = new InternetAddress(to); |
| 57 | + |
| 58 | + message.addRecipient(Message.RecipientType.TO, toAddress); |
| 59 | + |
| 60 | + message.setSubject(subject); |
| 61 | + message.setText(body); |
| 62 | + |
| 63 | + Transport transport = session.getTransport("smtp"); |
| 64 | + |
| 65 | + transport.connect(); |
| 66 | + |
| 67 | + transport.sendMessage(message, message.getAllRecipients()); |
| 68 | + transport.close(); |
| 69 | + } |
| 70 | +} |
0 commit comments