use of javax.mail.Transport in project spring-framework by spring-projects.
the class JavaMailSenderImpl method doSend.
/**
* Actually send the given array of MimeMessages via JavaMail.
* @param mimeMessages MimeMessage objects to send
* @param originalMessages corresponding original message objects
* that the MimeMessages have been created from (with same array
* length and indices as the "mimeMessages" array), if any
* @throws org.springframework.mail.MailAuthenticationException
* in case of authentication failure
* @throws org.springframework.mail.MailSendException
* in case of failure when sending a message
*/
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
Map<Object, Exception> failedMessages = new LinkedHashMap<>();
Transport transport = null;
try {
for (int i = 0; i < mimeMessages.length; i++) {
// Check transport connection first...
if (transport == null || !transport.isConnected()) {
if (transport != null) {
try {
transport.close();
} catch (Exception ex) {
// Ignore - we're reconnecting anyway
}
transport = null;
}
try {
transport = connectTransport();
} catch (AuthenticationFailedException ex) {
throw new MailAuthenticationException(ex);
} catch (Exception ex) {
// Effectively, all remaining messages failed...
for (int j = i; j < mimeMessages.length; j++) {
Object original = (originalMessages != null ? originalMessages[j] : mimeMessages[j]);
failedMessages.put(original, ex);
}
throw new MailSendException("Mail server connection failed", ex, failedMessages);
}
}
// Send message via current transport...
MimeMessage mimeMessage = mimeMessages[i];
try {
if (mimeMessage.getSentDate() == null) {
mimeMessage.setSentDate(new Date());
}
String messageId = mimeMessage.getMessageID();
mimeMessage.saveChanges();
if (messageId != null) {
// Preserve explicitly specified message id...
mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
}
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
} catch (Exception ex) {
Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
failedMessages.put(original, ex);
}
}
} finally {
try {
if (transport != null) {
transport.close();
}
} catch (Exception ex) {
if (!failedMessages.isEmpty()) {
throw new MailSendException("Failed to close server connection after message failures", ex, failedMessages);
} else {
throw new MailSendException("Failed to close server connection after message sending", ex);
}
}
}
if (!failedMessages.isEmpty()) {
throw new MailSendException(failedMessages);
}
}
use of javax.mail.Transport in project LAMSADE-tools by LAntoine.
the class Util method sendEmail.
/**
* Sends an email to an address passed by parameter. If there is an error
* other than lack of an Internet connection, the program will exit with a
* stack trace.
*
* @param to_address
* the address to send the email to
* @param filename
* if it's not empty, it will send the file referenced to by the
* filename as an attachment
* @throws IllegalStateException
* @returns 0 if it all went well, -1 if there was some error.
*/
public static int sendEmail(String to_address, String filename) throws IllegalStateException {
int smtp_port = 465;
String smtp_host = "smtp.gmail.com";
String smtp_username = "lamsade.tools@gmail.com";
String smtp_password = "z}}VC_-7{3bk^?*q^qZ4Z>G<5cgN&un&@>wU`gyza]kR(2v/&j!*6*s?H[^w=52e";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtp_host);
props.put("mail.smtps.auth", true);
props.put("mail.smtps.starttls.enable", true);
props.put("mail.smtps.debug", true);
Session session = Session.getInstance(props, null);
Message message = new MimeMessage(session);
logger.info("Trying to send an email to " + to_address);
try {
try {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to_address));
} catch (AddressException e) {
logger.error("There is a problem with the address");
throw new IllegalStateException(e);
}
message.setFrom(new InternetAddress(smtp_username));
if (filename == "") {
message.setSubject("Email Test Subject");
message.setText("Email Test Body");
} else {
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("Une conference a été partagée avec vous", "text/html");
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = filename;
attachPart.attachFile(attachFile);
// adds parts to the multipart
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);
// sets the multipart as message's content
message.setContent(multipart);
}
Transport transport = session.getTransport("smtps");
try {
transport.connect(smtp_host, smtp_port, smtp_username, smtp_password);
} catch (MessagingException e) {
logger.debug("There seems to be a problem with the connection. Try again later");
return -1;
}
try {
transport.sendMessage(message, message.getAllRecipients());
} catch (SendFailedException e) {
logger.error("Something went wrong trying to send the message");
throw new IllegalStateException(e);
}
transport.close();
} catch (MessagingException e) {
logger.error("Something went wrong with building the message");
throw new IllegalStateException(e);
} catch (IOException e) {
logger.error("Error in trying to add the attachment");
throw new IllegalStateException(e);
}
logger.info("Email sent successfully");
return 0;
}
use of javax.mail.Transport in project opennms by OpenNMS.
the class JavaMailer method sendMessage.
/**
* Send message.
*
* @param message a {@link javax.mail.Message} object.
* @throws org.opennms.javamail.JavaMailerException if any.
*/
public void sendMessage(Message message) throws JavaMailerException {
Transport t = null;
try {
t = getSession().getTransport(getTransport());
LOG.debug("for transport name '{}' got: {}@{}", getTransport(), t.getClass().getName(), Integer.toHexString(t.hashCode()));
LoggingTransportListener listener = new LoggingTransportListener();
t.addTransportListener(listener);
if (t.getURLName().getProtocol().equals("mta")) {
// JMTA throws an AuthenticationFailedException if we call connect()
LOG.debug("transport is 'mta', not trying to connect()");
} else if (isAuthenticate()) {
LOG.debug("authenticating to {}", getMailHost());
t.connect(getMailHost(), getSmtpPort(), getUser(), getPassword());
} else {
LOG.debug("not authenticating to {}", getMailHost());
t.connect(getMailHost(), getSmtpPort(), null, null);
}
t.sendMessage(message, message.getAllRecipients());
listener.assertAllMessagesDelivered();
} catch (NoSuchProviderException e) {
LOG.error("Couldn't get a transport: {}", e, e);
throw new JavaMailerException("Couldn't get a transport: " + e, e);
} catch (MessagingException e) {
LOG.error("Java Mailer messaging exception: {}", e, e);
throw new JavaMailerException("Java Mailer messaging exception: " + e, e);
} finally {
try {
if (t != null && t.isConnected()) {
t.close();
}
} catch (MessagingException e) {
throw new JavaMailerException("Java Mailer messaging exception on transport close: " + e, e);
}
}
}
use of javax.mail.Transport in project nhin-d by DirectProject.
the class MessageServiceImplService method sendMessage.
@Override
public /**
* Converts an incoming WS request into an email message and sends it to the configured
* email server
*/
SendResponseType sendMessage(EmailType body) {
if (log.isDebugEnabled())
log.debug("Enter");
SendResponseType response = new SendResponseType();
checkAuth(response);
if (response.getError() == null) {
log.info("Auth success");
Multipart mailBody;
MimeBodyPart mainBody;
MimeBodyPart mimeAttach;
String fromaddress = body.getHead().getFrom().getAddress();
log.info("Got FROM address");
try {
InternetAddress addressFrom;
addressFrom = new InternetAddress(fromaddress.toString());
if (log.isDebugEnabled())
log.debug("Sender: " + addressFrom);
InternetAddress[] addressTo = new InternetAddress[1];
int i = 0;
for (AddressType recipient : body.getHead().getTo()) {
addressTo[i] = new InternetAddress(recipient.getAddress());
if (log.isDebugEnabled())
log.debug("Recipient: " + addressTo[i]);
i++;
}
Session session = Session.getInstance(smtpProps, new SMTPAuthenticator());
// Build message object
MimeMessage mimeMsg = new MimeMessage(session);
mimeMsg.setFrom(addressFrom);
mimeMsg.setRecipients(Message.RecipientType.TO, addressTo);
if (body.getHead().getSubject() != null) {
mimeMsg.setSubject(body.getHead().getSubject());
} else {
mimeMsg.setSubject("Direct message");
}
mailBody = new MimeMultipart();
mainBody = new MimeBodyPart();
if (body.getBody().getText() != null) {
mainBody.setText(body.getBody().getText());
} else {
mainBody.setText("");
}
mailBody.addBodyPart(mainBody);
copyAttachments(body, mailBody);
mimeMsg.setContent(mailBody);
DirectMimeMessage dMsg = new DirectMimeMessage(mimeMsg, getSenderHost());
dMsg.updateMessageID();
Transport transport;
if (getUseTLSforSMTP().equals("SOCKET")) {
transport = session.getTransport("smtps");
} else {
transport = session.getTransport("smtp");
}
transport.connect();
try {
transport.sendMessage(dMsg, addressTo);
// Transport.send(dMsg);
response.setMessageID(dMsg.getMessageID());
transport.close();
} finally {
transport.close();
}
} catch (AddressException e) {
ErrorType et = new ErrorType();
et.setCode(ErrorCodeType.ADDRESSING);
et.setMessage(e.getMessage());
response.setError(et);
log.error(e);
} catch (MessagingException e) {
ErrorType et = new ErrorType();
et.setCode(ErrorCodeType.MESSAGING);
et.setMessage(e.getMessage());
response.setError(et);
log.error(e);
} catch (Exception e) {
ErrorType et = new ErrorType();
et.setCode(ErrorCodeType.SYSTEM);
et.setMessage(e.getMessage());
response.setError(et);
log.error(e);
e.printStackTrace();
}
}
return response;
}
use of javax.mail.Transport in project nhin-d by DirectProject.
the class MailSender method main.
public static void main(String[] args) {
if (args.length == 0) {
// error out
} else {
if (args[0].compareTo("-sign") == 0) {
try {
Properties p = new Properties();
//p.put("mail.smtp.host", "localhost");
//p.put("mail.smtp.port", "10025");
p.put("mail.smtp.host", "smtprr.cerner.com");
p.setProperty("mail.debug", "true");
// start a session
javax.mail.Session session = javax.mail.Session.getDefaultInstance(p, null);
// create the message
// create the message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("gmeyer@cerner.com"));
message.addRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress("gm2552@securehealthemail.com"), new InternetAddress("ryan@securehealthemail.com") });
message.setSubject("Test subject:");
String text = "This is some test text to attempt to encypt and sign.";
message.setText(text);
Transport trans = session.getTransport("smtp");
trans.connect();
message.saveChanges();
trans.sendMessage(message, message.getAllRecipients());
trans.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
String msgText = readResource("EncryptedMessage.txt");
Properties p = new Properties();
p.put("mail.smtp.host", "localhost");
p.put("mail.smtp.port", "10025");
// start a session
javax.mail.Session session = javax.mail.Session.getInstance(p, null);
// create the message
MimeMessage message = new MimeMessage(session, new ByteArrayInputStream(msgText.getBytes("ASCII")));
Transport trans = session.getTransport("smtp");
trans.connect();
message.saveChanges();
trans.sendMessage(message, message.getAllRecipients());
trans.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Aggregations