use of com.sun.mail.smtp.SMTPTransport in project greenmail by greenmail-mail-test.
the class SMTPCommandTest method mailSenderAUTHSuffix.
@Test
public void mailSenderAUTHSuffix() throws IOException, MessagingException {
Session smtpSession = greenMail.getSmtp().createSession();
try (SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL)) {
// Closed by transport
Socket smtpSocket = new Socket(hostAddress, port);
smtpTransport.connect(smtpSocket);
assertThat(smtpTransport.isConnected()).isTrue();
smtpTransport.issueCommand("MAIL FROM: <test.test@test.net> AUTH <>", -1);
assertThat("250 OK").isEqualToNormalizingWhitespace(smtpTransport.getLastServerResponse());
}
}
use of com.sun.mail.smtp.SMTPTransport in project mathspring by center-for-knowledge-communication.
the class SendEM method send.
public boolean send(Connection connection, String t, String f, String subj, String b, String h) {
String to = "";
String[] toArray = t.split(",");
String from = "";
String subject = "";
String body = "";
String[] filenames = new String[0];
String[][] filenamesAndData = new String[0][0];
String host = "";
to = t;
from = f;
subject = subj;
body = b;
host = h;
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
if (filenames.length > 0) {
try {
// Get session
Session session = Session.getInstance(props, null);
// Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (toArray.length > 0) {
for (int i = 0; i < toArray.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toArray[i]));
}
} else {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
//
// Part two is attachment(s)
//
int numAttachments = filenames.length;
for (int i = 0; i < numAttachments; i++) {
// Create second body part
messageBodyPart = new MimeBodyPart();
// Get the attachment
DataSource source = new FileDataSource(filenames[i]);
// Set the data handler to the attachment
messageBodyPart.setDataHandler(new DataHandler(source));
// Set the filename
String fs = "/";
String tempName = filenames[i].substring(filenames[i].lastIndexOf(fs) + 1);
messageBodyPart.setFileName(tempName);
// Add part two
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
}
// Send the message
SMTPTransport tp = (SMTPTransport) session.getTransport("smtps");
tp.connect(host, "mathspring@cs.umass.edu", setPwd(connection));
tp.sendMessage(message, message.getAllRecipients());
tp.close();
// Inform user that mail was sent successfully
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else if (filenamesAndData.length > 0) {
try {
// Get session
Session session = Session.getInstance(props, null);
// Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (toArray.length > 0) {
for (int i = 0; i < toArray.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toArray[i]));
}
} else {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
//
// Part two is attachment(s)
//
int numAttachments = filenamesAndData.length;
for (int i = 0; i < numAttachments; i++) {
// Create second body part
messageBodyPart = new MimeBodyPart();
// Get the attachment
messageBodyPart.setText(filenamesAndData[i][1]);
// Set the filename
messageBodyPart.setFileName(filenamesAndData[i][0]);
// Add part two
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
}
// Send the message
SMTPTransport tp = (SMTPTransport) session.getTransport("smtps");
tp.connect(host, "mathspring@cs.umass.edu", setPwd(connection));
tp.sendMessage(message, message.getAllRecipients());
tp.close();
// Inform user that mail was sent successfully
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
try {
// Get session
Session session = Session.getInstance(props, null);
// Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (toArray.length > 0) {
for (int i = 0; i < toArray.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toArray[i]));
}
} else {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
}
message.setSubject(subject);
// Fill the message
message.setText(body);
// Send the message
SMTPTransport tp = (SMTPTransport) session.getTransport("smtps");
tp.connect(host, "mathspring@cs.umass.edu", setPwd(connection));
tp.sendMessage(message, message.getAllRecipients());
tp.close();
// Inform user that mail was sent successfully
return true;
} catch (Exception e) {
// System.out.println(e.getMessage()+" error mailer ");
e.printStackTrace();
return false;
}
}
}
use of com.sun.mail.smtp.SMTPTransport in project ph-web by phax.
the class MainSMTPSend method main.
/*
* Example of how to extend the SMTPTransport class. This example illustrates
* how to issue the XACT command before the SMTPTransport issues the DATA
* command. public static class SMTPExtension extends SMTPTransport { public
* SMTPExtension(Session session, URLName url) { super(session, url); // to
* check that we're being used System.out.println("SMTPExtension: constructed"
* ); } protected synchronized OutputStream data() throws MessagingException {
* if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return
* super.data(); } }
*/
@SuppressWarnings("resource")
public static void main(final String[] argv) {
String to, subject = null, from = null, cc = null, bcc = null, url = null;
String mailhost = null;
final String mailer = "smtpsend";
String file = null;
String protocol = null, host = null, user = null, password = null;
// name of folder in which to record mail
String record = null;
boolean debug = false;
boolean verbose = false;
boolean auth = false;
String prot = "smtp";
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int optind;
/*
* Process command line arguments.
*/
for (optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-M")) {
mailhost = argv[++optind];
} else if (argv[optind].equals("-f")) {
record = argv[++optind];
} else if (argv[optind].equals("-a")) {
file = argv[++optind];
} else if (argv[optind].equals("-s")) {
subject = argv[++optind];
} else if (argv[optind].equals("-o")) {
// originator
from = argv[++optind];
} else if (argv[optind].equals("-c")) {
cc = argv[++optind];
} else if (argv[optind].equals("-b")) {
bcc = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-d")) {
debug = true;
} else if (argv[optind].equals("-v")) {
verbose = true;
} else if (argv[optind].equals("-A")) {
auth = true;
} else if (argv[optind].equals("-S")) {
prot = "smtps";
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
System.out.println("\t[-v] [-A] [-S] [address]");
System.exit(1);
} else {
break;
}
}
try {
/*
* Prompt for To and Subject, if not specified.
*/
if (optind < argv.length) {
// - concatenate all remaining arguments
to = argv[optind];
System.out.println("To: " + to);
} else {
System.out.print("To: ");
System.out.flush();
to = in.readLine();
}
if (subject == null) {
System.out.print("Subject: ");
System.out.flush();
subject = in.readLine();
} else {
System.out.println("Subject: " + subject);
}
/*
* Initialize the JavaMail Session.
*/
final Properties props = IPrivilegedAction.systemGetProperties().invokeSafe();
if (mailhost != null)
props.put("mail." + prot + ".host", mailhost);
if (auth)
props.put("mail." + prot + ".auth", "true");
/*
* Create a Provider representing our extended SMTP transport and set the
* property to use our provider. Provider p = new
* Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension",
* "JavaMail demo", "no version"); props.put("mail." + prot + ".class",
* "smtpsend$SMTPExtension");
*/
// Get a Session object
final Session session = Session.getInstance(props, null);
if (debug)
session.setDebug(true);
/*
* Register our extended SMTP transport. session.addProvider(p);
*/
/*
* Construct the message and send it.
*/
final Message msg = new MimeMessage(session);
if (from != null)
msg.setFrom(new InternetAddress(from));
else
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
if (cc != null)
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
if (bcc != null)
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
msg.setSubject(subject);
final String text = collect(in);
if (file != null) {
// Attach the specified file.
// We need a multipart message to hold the attachment.
final MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(text);
final MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.attachFile(file);
final MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
} else {
// If the desired charset is known, you can use
// setText(text, charset)
msg.setText(text);
}
msg.setHeader("X-Mailer", mailer);
msg.setSentDate(new Date());
/*
* The simple way to send a message is this: Transport.send(msg); But
* we're going to use some SMTP-specific features for demonstration
* purposes so we need to manage the Transport object explicitly.
*/
try (final SMTPTransport t = (SMTPTransport) session.getTransport(prot)) {
if (auth)
t.connect(mailhost, user, password);
else
t.connect();
t.sendMessage(msg, msg.getAllRecipients());
if (verbose)
System.out.println("Response: " + t.getLastServerResponse());
}
System.out.println("\nMail was sent successfully.");
/*
* Save a copy of the message, if requested.
*/
if (record != null) {
// Get a Store object
Store store = null;
if (url != null) {
final URLName urln = new URLName(url);
store = session.getStore(urln);
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();
// Connect
if (host != null || user != null || password != null)
store.connect(host, user, password);
else
store.connect();
}
// Get record Folder. Create if it does not exist.
final Folder folder = store.getFolder(record);
if (folder == null) {
System.err.println("Can't get record folder.");
System.exit(1);
}
if (!folder.exists())
folder.create(Folder.HOLDS_MESSAGES);
final Message[] msgs = new Message[1];
msgs[0] = msg;
folder.appendMessages(msgs);
System.out.println("Mail was recorded successfully.");
}
} catch (final MessagingException | IOException e) {
/*
* Handle SMTP-specific exceptions.
*/
if (e instanceof SendFailedException) {
MessagingException sfe = (MessagingException) e;
if (sfe instanceof SMTPSendFailedException) {
final SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe;
System.out.println("SMTP SEND FAILED:");
if (verbose)
System.out.println(ssfe.toString());
System.out.println(" Command: " + ssfe.getCommand());
System.out.println(" RetCode: " + ssfe.getReturnCode());
System.out.println(" Response: " + ssfe.getMessage());
} else {
if (verbose)
System.out.println("Send failed: " + sfe.toString());
}
Exception ne;
while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) {
sfe = (MessagingException) ne;
if (sfe instanceof SMTPAddressFailedException) {
final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe;
System.out.println("ADDRESS FAILED:");
if (verbose)
System.out.println(ssfe.toString());
System.out.println(" Address: " + ssfe.getAddress());
System.out.println(" Command: " + ssfe.getCommand());
System.out.println(" RetCode: " + ssfe.getReturnCode());
System.out.println(" Response: " + ssfe.getMessage());
} else if (sfe instanceof SMTPAddressSucceededException) {
System.out.println("ADDRESS SUCCEEDED:");
final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe;
if (verbose)
System.out.println(ssfe.toString());
System.out.println(" Address: " + ssfe.getAddress());
System.out.println(" Command: " + ssfe.getCommand());
System.out.println(" RetCode: " + ssfe.getReturnCode());
System.out.println(" Response: " + ssfe.getMessage());
}
}
} else {
System.out.println("Got Exception: " + e);
if (verbose)
e.printStackTrace();
}
}
}
use of com.sun.mail.smtp.SMTPTransport in project opentheso by miledrousset.
the class ForgetPasswordHelper method envoiEmail.
/**
* Envoi une email a "nonUsu" a la direcction "email" pour l'indiquer son
* nouvelle "pass"
*
* @param email
* @param pass
* @throws MessagingException
*/
private void envoiEmail(String email, String pass, String pseudo) throws MessagingException {
ResourceBundle bundlePref = getBundlePref();
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.transport.protocol", bundlePref.getString("protocolMail"));
props.setProperty("mail.smtp.host", bundlePref.getString("hostMail"));
props.setProperty("mail.smtp.port", bundlePref.getString("portMail"));
props.setProperty("mail.smtp.auth", bundlePref.getString("authMail"));
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(bundlePref.getString("mailFrom")));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
// / mot.titlePass
msg.setSubject(emailTitle);
msg.setText(emailMessage + pass + "\n" + pseudoMessage + pseudo);
SMTPTransport transport = (SMTPTransport) session.getTransport(bundlePref.getString("transportMail"));
transport.connect();
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
transport.close();
/*
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.transport.protocol", user.getNodePreference().getProtcolMail());
props.setProperty("mail.smtp.host", user.getNodePreference().getHostMail());
Integer temp = user.getNodePreference().getPortMail();
props.setProperty("mail.smtp.port", temp.toString());
Boolean temp2 = user.getNodePreference().isAuthMail();
props.setProperty("mail.smtp.auth",temp2.toString());
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(user.getNodePreference().getMailFrom()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
msg.setSubject(emailTitle); /// mot.titlePass
msg.setText(emailMessage + pass + "\n" + pseudoMessage + pseudo);
SMTPTransport transport = (SMTPTransport) session.getTransport(user.getNodePreference().getTransportMail());
transport.connect();
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
transport.close();
*/
}
use of com.sun.mail.smtp.SMTPTransport in project opentheso by miledrousset.
the class PreferencesMail method sendMessage.
/**
* sendmessage
* #JM
* Doit envoyer le message MimeMessage msg qui a été préalablement configuré
* avec les autres méthodes de la classe
*/
public void sendMessage() {
SMTPTransport transport = null;
try {
transport = (SMTPTransport) session.getTransport(properties.getProperty("transportMail"));
try {
transport.connect();
try {
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
} finally {
transport.close();
}
} catch (MessagingException e) {
log.error("error while connecting or sending message on transport ", e);
}
} catch (NoSuchProviderException e) {
log.error("error while geting transport from session :" + session.toString() + " properties" + properties.getProperty("transportMail"), e);
}
status = true;
}
Aggregations