com.sun.mail.smtp.SMTPTransport Java Examples
The following examples show how to use
com.sun.mail.smtp.SMTPTransport.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EMail.java From TakServer with GNU General Public License v2.0 | 7 votes |
public static void send(String to, String sub, String msg) { Properties prop = System.getProperties(); prop.put("mail.smtps.host", host); prop.put("mail.smtps.auth", "true"); Session session = Session.getInstance(prop); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(sub); message.setText(msg); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect(host, user, password); t.sendMessage(message, message.getAllRecipients()); t.close(); System.out.println("Email sent to "+to); } catch (MessagingException ex) { Logger.getLogger(EMail.class.getName()).log(Level.SEVERE, null, ex); } }
Example #2
Source File: SendingMailThroughGmailSMTPServer.java From hellokoding-courses with MIT License | 6 votes |
void sendMail(String smtpServerHost, String smtpServerPort, String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) { try { Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", smtpServerPort); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props); session.setDebug(true); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail)); msg.setSubject(subject); msg.setContent(body, "text/html"); SMTPTransport transport = new SMTPTransport(session, null); transport.connect(smtpServerHost, smtpUserName, null); transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235); transport.sendMessage(msg, msg.getAllRecipients()); } catch (Exception ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex); } }
Example #3
Source File: MailDelivrerToHost.java From james-project with Apache License 2.0 | 6 votes |
private void closeTransport(Mail mail, HostAddress outgoingMailServer, SMTPTransport transport) { if (transport != null) { try { // James-899: transport.close() sends QUIT to the server; if that fails // (e.g. because the server has already closed the connection) the message // should be considered to be delivered because the error happened outside // of the mail transaction (MAIL, RCPT, DATA). transport.close(); } catch (MessagingException e) { LOGGER.error("Warning: could not close the SMTP transport after sending mail ({}) to {} at {} for {}; " + "probably the server has already closed the connection. Message is considered to be delivered. Exception: {}", mail.getName(), outgoingMailServer.getHostName(), outgoingMailServer.getHost(), mail.getRecipients(), e.getMessage()); } transport = null; } }
Example #4
Source File: FenixInitializer.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 6 votes |
private void registerHealthchecks() { SystemResource.registerHealthcheck(new Healthcheck() { @Override public String getName() { return "SMTP"; } @Override protected Result check() throws Exception { final Properties properties = new Properties(); properties.put("mail.transport.protocol", "smtp"); Transport transport = Session.getInstance(properties).getTransport(); transport.connect(FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost(), null, null); String response = ((SMTPTransport) transport).getLastServerResponse(); transport.close(); return Result.healthy("SMTP server returned response: " + response); } }); }
Example #5
Source File: ForgotPassword.java From ShoppingCartinJava with MIT License | 5 votes |
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; // Get a Properties object Properties props = System.getProperties(); props.setProperty("mail.smtps.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session session = Session.getInstance(props, null); // -- Create a new message -- final MimeMessage msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(username + "@gmail.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); if (ccEmail.length() > 0) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false)); } msg.setSubject(title); msg.setText(message, "utf-8"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", username, password); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
Example #6
Source File: MailDelivrerToHost.java From james-project with Apache License 2.0 | 5 votes |
private void connect(HostAddress outgoingMailServer, SMTPTransport transport) throws MessagingException { if (configuration.getAuthUser() != null) { transport.connect(outgoingMailServer.getHostName(), configuration.getAuthUser(), configuration.getAuthPass()); } else { transport.connect(); } }
Example #7
Source File: MailDelivrerToHost.java From james-project with Apache License 2.0 | 5 votes |
private MimeMessage adaptToTransport(MimeMessage message, SMTPTransport transport) throws MessagingException { if (shouldAdapt(transport)) { try { converter7Bit.convertTo7Bit(message); } catch (IOException e) { LOGGER.error("Error during the conversion to 7 bit.", e); } } return message; }
Example #8
Source File: MailDelivrerToHost.java From james-project with Apache License 2.0 | 5 votes |
private boolean shouldAdapt(SMTPTransport transport) { // If the transport is a SMTPTransport (from sun) some performance enhancement can be done. // If the transport is not the one developed by Sun we are not sure of how it handles the 8 bit mime stuff, so I // convert the message to 7bit. return !transport.getClass().getName().endsWith(".SMTPTransport") || !transport.supportsExtension(BIT_MIME_8); // if the message is already 8bit or binary and the server doesn't support the 8bit extension it has to be converted // to 7bit. Javamail api doesn't perform that conversion, but it is required to be a rfc-compliant smtp server. }
Example #9
Source File: EmailUtil.java From kspl-selenium-helper with GNU General Public License v3.0 | 5 votes |
private void send(Message msg) throws MessagingException { SMTPTransport t = (SMTPTransport) session.getTransport("smtps"); try { t.connect(this.getHost(), this.getFrom(), this.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); } finally { System.out.println("Response: " + t.getLastServerResponse()); t.close(); } }
Example #10
Source File: SMTPCommandTest.java From greenmail with Apache License 2.0 | 5 votes |
@Test public void mailSenderEmpty() throws IOException, MessagingException { Session smtpSession = greenMail.getSmtp().createSession(); SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL); try { Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport smtpTransport.connect(smtpSocket); assertThat(smtpTransport.isConnected(), is(equalTo(true))); smtpTransport.issueCommand("MAIL FROM: <>", -1); assertThat("250 OK", equalToCompressingWhiteSpace(smtpTransport.getLastServerResponse())); } finally { smtpTransport.close(); } }
Example #11
Source File: SMTPCommandTest.java From greenmail with Apache License 2.0 | 5 votes |
@Test public void authLogin() throws IOException, MessagingException, UserException { Session smtpSession = greenMail.getSmtp().createSession(); SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL); try { Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport smtpTransport.connect(smtpSocket); assertThat(smtpTransport.isConnected(), is(equalTo(true))); // Should fail, as user does not exist smtpTransport.issueCommand("AUTH LOGIN ", 334); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */)); smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */)); smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_CREDENTIALS_INVALID)); // Try again but create user greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass"); smtpTransport.issueCommand("AUTH LOGIN ", 334); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */)); smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */)); smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1); assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_SUCCEDED)); } finally { smtpTransport.close(); } }
Example #12
Source File: SMTPCommandTest.java From greenmail with Apache License 2.0 | 5 votes |
@Test public void mailSenderAUTHSuffix() throws IOException, MessagingException { Session smtpSession = greenMail.getSmtp().createSession(); SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL); try { Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport smtpTransport.connect(smtpSocket); assertThat(smtpTransport.isConnected(), is(equalTo(true))); smtpTransport.issueCommand("MAIL FROM: <[email protected]> AUTH <>", -1); assertThat("250 OK", equalToCompressingWhiteSpace(smtpTransport.getLastServerResponse())); } finally { smtpTransport.close(); } }
Example #13
Source File: EmailService.java From FairEmail with GNU General Public License v3.0 | 4 votes |
SMTPTransport getTransport() { return (SMTPTransport) iservice; }
Example #14
Source File: SendEmailSmtp.java From opentest with MIT License | 4 votes |
@Override public void run() { String server = this.readStringArgument("server"); String subject = this.readStringArgument("subject"); String body = this.readStringArgument("body"); String userName = this.readStringArgument("userName"); String password = this.readStringArgument("password"); String to = this.readStringArgument("to"); Integer port = this.readIntArgument("port", 25); Boolean useTls = this.readBooleanArgument("useTls", true); String cc = this.readStringArgument("cc", null); String from = this.readStringArgument("from", "[email protected]"); try { Properties prop = System.getProperties(); prop.put("mail.smtp.host", server); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.port", port.toString()); Session session = Session.getInstance(prop, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } msg.setSubject(subject); msg.setText(body); msg.setSentDate(new Date()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); transport.setStartTLS(useTls); transport.connect(server, userName, password); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception exc) { throw new RuntimeException("Failed to send email", exc); } }
Example #15
Source File: EmailSmtpConnector.java From mxisd with GNU Affero General Public License v3.0 | 4 votes |
@Override public void send(String senderAddress, String senderName, String recipient, String content) { if (StringUtils.isBlank(senderAddress)) { throw new FeatureNotAvailable("3PID Email identity: sender address is empty - " + "You must set a value for notifications to work"); } if (StringUtils.isBlank(content)) { throw new InternalServerError("Notification content is empty"); } try { InternetAddress sender = new InternetAddress(senderAddress, senderName); MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8)); // We must encode our headers ourselves as we have no guarantee that they were in the provided data. // This is required to support UTF-8 characters from user display names or room names in the subject header per example Enumeration<Header> headers = msg.getAllHeaders(); while (headers.hasMoreElements()) { Header header = headers.nextElement(); msg.setHeader(header.getName(), MimeUtility.encodeText(header.getValue())); } msg.setHeader("X-Mailer", MimeUtility.encodeText(Mxisd.Agent)); msg.setSentDate(new Date()); msg.setFrom(sender); msg.setRecipients(Message.RecipientType.TO, recipient); msg.saveChanges(); log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); if (cfg.getTls() < 3) { transport.setStartTLS(cfg.getTls() > 0); transport.setRequireStartTLS(cfg.getTls() > 1); } log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort()); if (StringUtils.isAllEmpty(cfg.getLogin(), cfg.getPassword())) { log.info("Not using SMTP authentication"); transport.connect(); } else { log.info("Using SMTP authentication"); transport.connect(cfg.getLogin(), cfg.getPassword()); } try { transport.sendMessage(msg, InternetAddress.parse(recipient)); log.info("Invite to {} was sent", recipient); } finally { transport.close(); } } catch (UnsupportedEncodingException | MessagingException e) { throw new RuntimeException("Unable to send e-mail invite to " + recipient, e); } }
Example #16
Source File: BigAttachmentTest.java From subethasmtp with Apache License 2.0 | 4 votes |
/** */ public void testAttachments() throws Exception { if (BIGFILE_PATH.equals(TO_CHANGE)) { log.error("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !"); } assertNotSame("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !", TO_CHANGE, BIGFILE_PATH); Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "localhost"); props.setProperty("mail.smtp.port", SMTP_PORT+""); Session session = Session.getInstance(props); MimeMessage baseMsg = new MimeMessage(session); MimeBodyPart bp1 = new MimeBodyPart(); bp1.setHeader("Content-Type", "text/plain"); bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\""); // Attach the file MimeBodyPart bp2 = new MimeBodyPart(); FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH); DataHandler dh = new DataHandler(fileAttachment); bp2.setDataHandler(dh); bp2.setFileName(fileAttachment.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bp1); multipart.addBodyPart(bp2); baseMsg.setFrom(new InternetAddress("Ted <[email protected]>")); baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress( "[email protected]")); baseMsg.setSubject("Test Big attached file message"); baseMsg.setContent(multipart); baseMsg.saveChanges(); log.debug("Send started"); Transport t = new SMTPTransport(session, new URLName("smtp://localhost:"+SMTP_PORT)); long started = System.currentTimeMillis(); t.connect(); t.sendMessage(baseMsg, new Address[] {new InternetAddress( "[email protected]")}); t.close(); started = System.currentTimeMillis() - started; log.info("Elapsed ms = "+started); WiserMessage msg = this.server.getMessages().get(0); assertEquals(1, this.server.getMessages().size()); assertEquals("[email protected]", msg.getEnvelopeReceiver()); File compareFile = File.createTempFile("attached", ".tmp"); log.debug("Writing received attachment ..."); FileOutputStream fos = new FileOutputStream(compareFile); ((MimeMultipart) msg.getMimeMessage().getContent()).getBodyPart(1).getDataHandler().writeTo(fos); fos.close(); log.debug("Checking integrity ..."); assertTrue(this.checkIntegrity(new File(BIGFILE_PATH), compareFile)); log.debug("Checking integrity DONE"); compareFile.delete(); }