how to send mail to a mailing list with java? - java

I want to send a mail to a mailing list every period of time (like every 40min or hour) with java on a unix server.
I'd like any code or tutorial to be able to do this.
Thanks

Sending a mail to a mailing list does not differ from sending a regular mail. The simplest way is to use commons-email. Check its examples.

JavaMail is the usual approach for this. You will need a SMTP-server for JavaMail to connect to.

String[] mailToId = {
"abc#mail.com",
"abc22#mail.com",
"abc33#mail.com"
};
for (int i = 0; i < mailToId.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToId[i]));;
}
In your java class you can use array of mail address and one by one mail address can call using for loop.
Within the for loop you can call
message.addRecipient();
method with array name.
look at the above example:

If it is not necessary to USE SMTP - java mail enough
Simple example
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
private static String host = "";
private static String user = "";
private static String password = "";
private static int port = 465;
private static String from = "";
private static String to = "";
private static String auth = "true";
private static String debug = "false";
private static String socket_factory = "javax.net.ssl.SSLSocketFactory";
private static String subject = "";
private static String text = "";
/**
* Constructor. Fields - parameters for send mail.
*
* #param host - mail server.
* #param user - user
* #param password - login
* #param port - port
* #param from - mail from address
* #param to - mail to address
* #param subject - subject
* #param text - text of mail
*/
public MailSender(String host, String user, String password, int port,
String from, String to, String subject, String text) {
if (!host.isEmpty())
setHost(host);
if (!user.isEmpty())
setUser(user);
if (!password.isEmpty())
setPassword(password);
if (port == 0)
setPort(port);
if (!from.isEmpty())
setFrom(from);
if (!to.isEmpty())
setTo(to);
if (!subject.isEmpty())
setSubject(subject);
if (!text.isEmpty())
setText(text);
}
/**
* Send mail with parameters from constructor.
*/
public void send() {
// Use Properties object to set environment properties
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", getHost());
props.put("mail.smtp.port", getPort());
props.put("mail.smtp.user", getUser());
props.put("mail.smtp.auth", getAuth());
props.put("mail.smtp.starttls.enable","true");//for gmail?
props.put("mail.smtp.debug", getDebug());
props.put("mail.smtp.socketFactory.port", getPort());
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");//for gmail?
props.put("mail.smtp.socketFactory.fallback", "false");
try {
// Obtain the default mail session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(new Boolean(getDebug()));
// Construct the mail message
MimeMessage message = new MimeMessage(session);
message.setText(getText());
message.setSubject(getSubject());
message.setFrom(new InternetAddress(getFrom()));
message
.addRecipient(RecipientType.TO,
new InternetAddress(getTo()));
message.saveChanges();
// Use Transport to deliver the message
Transport transport = session.getTransport("smtp");
transport.connect(getHost(), getUser(), getPassword());
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getHost() {
return host;
}
public static void setHost(String host) {
MailSender.host = host;
}
public static String getUser() {
return user;
}
public static void setUser(String user) {
MailSender.user = user;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
MailSender.password = password;
}
public static int getPort() {
return port;
}
public static void setPort(int port) {
MailSender.port = port;
}
public static String getFrom() {
return from;
}
public static void setFrom(String from) {
MailSender.from = from;
}
public static String getTo() {
return to;
}
public static void setTo(String to) {
MailSender.to = to;
}
public static String getAuth() {
return auth;
}
public static void setAuth(String auth) {
MailSender.auth = auth;
}
public static String getDebug() {
return debug;
}
public static void setDebug(String debug) {
MailSender.debug = debug;
}
public static String getSocket_factory() {
return socket_factory;
}
public static void setSocket_factory(String socketFactory) {
socket_factory = socketFactory;
}
public static String getSubject() {
return subject;
}
public static void setSubject(String subject) {
MailSender.subject = subject;
}
public static String getText() {
return text;
}
public static void setText(String text) {
MailSender.text = text;
}

Related

Java Twitch IRC Bot

So I'm working on a basic Twitch Bot for my channel and the code is as follows:
Config.java
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
public class Config {
private static final String OAUTH = "MYOAUTHHERE";
private static final String ADRESS = "irc.chat.twitch.tv.";
private static final int PORT = 6667;
private static final String channelName = "#MYCHANNELNAMEHERE";
public static void main(String[] args) throws NickAlreadyInUseException, IOException, IrcException {
TwitchBot bot = new TwitchBot();
bot.setVerbose(true);
bot.connect(ADRESS, PORT, OAUTH);
// bot.onMessage(channelName, "Bot", channelName, channelName, channelName);
System.out.println("Connected!");
bot.joinChannel(channelName);
System.out.println("Successfully joined channel!");
bot.sendMessage(channelName, "Hello, I am a bot");
}
}
TwitchBot.java
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
private static final String channelName = "#MYCHANNELNAME";
private final String botName = "THEBOTNAME";
public TwitchBot() {
this.setName(botName);
this.setLogin(botName);
}
public String getchannelName() {
return channelName;
}
#Override
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if (message.equalsIgnoreCase("time")) {
String time = new java.util.Date().toString();
sendMessage(channel, sender + ": The time is now " + time);
}
}
}
The console displays "Connected!" and "Successfully joined channel" however the bot is unresponsive, and is not in the channel I specified. It also does not print "Hello I am a bot" in the chat.
There are few things to consider about Twitch.
Your email must be validated. Settings -> Profile -> Profile Settings
Channel names must be entered as lowercase.
Nickname are useless, twitch are using your profile nickname.
Twitch uses IRCv3 Client Capability Negotiation aka CAP, which means you should be use it as well.
You should only try enter existing channels, otherwise the server will ignore your JOIN channel.
Twitch, allow themselves the opportunity to change your nickname while you logged in, which means, that the expected nick results, provided by TwitchBot class, can, and probably be incorrect if you supply any name different from your logged in profile nickname.
Twitch IRC Capabilities, can be found Here, here are few..
membership: JOIN, MODE, NAMES, PART
tags: PRIVMSG, etc'
You should add those CAP, first thing you are logged in.
Important Notice: PIRCBot, doesn't look to support twitch PRIVMSG format, which means onMessage callback, will not be called. which leaves you to handle the parsing of received messages, through handleLine general callback.
Code as been updated to apply to above changes, and you should set the final variables in order it to work.
TwitchBot.java
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
private final String requestedNick;
private String realNick;
private String realServer;
public TwitchBot(String nick) {
this.requestedNick = nick;
setName(this.requestedNick);
setLogin(this.requestedNick);
}
#Override
protected void onConnect() {
super.onConnect();
System.out.println("Connected!");
// Sending special capabilities.
sendRawLine("CAP REQ :twitch.tv/membership");
sendRawLine("CAP REQ :twitch.tv/commands");
sendRawLine("CAP REQ :twitch.tv/tags");
}
#Override
protected void handleLine(String line) {
super.handleLine(line);
if (line.startsWith(":")) {
String[] recvLines = line.split(" ");
// First message is 001, extract logged in information.
if (recvLines[1].equals("001")) {
this.realServer = recvLines[0].substring(1);
this.realNick = recvLines[2];
System.out.println("realServer: " + this.realServer);
System.out.println("realNick: " + this.realNick);
}
}
}
#Override
protected void onJoin(String channel, String sender, String login, String hostname) {
super.onJoin(channel, sender, login, hostname);
if (sender.equals(this.realNick)){
System.out.println("Successfully joined: " + channel);
}
}
#Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
if (message.equalsIgnoreCase("time")) {
String time = new java.util.Date().toString();
sendMessage(channel, sender + ": The time is now " + time);
}
}
}
goFile.java
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
public class goFile {
private static final String OAUTH = "MYOAUTHHERE";
private static final String ADDRESS = "irc.twitch.tv.";
private static final int PORT = 6667;
private static final String Nick = "MYNICKHERE";
private static final String Channel = "#MYCHANNELHERE";
public static void main(String[] args) throws NickAlreadyInUseException, IOException, IrcException {
TwitchBot bot = new TwitchBot(Nick);
bot.setVerbose(true);
bot.connect(ADDRESS, PORT, OAUTH);
bot.joinChannel(Channel);
bot.sendMessage(Channel, "Hello, I am a bot");
}
}

org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized while calling NTLM service from WSO2 ESB

I am trying to call NTLM service from WSO2 ESB. I have created a custom mediator for NTLM access but getting "org.apache.axis2.AxisFault: Transport error: 401 Error: Unauthorized" every time, any help will be much appreciated.
Code:
package mbie.poc;
import java.util.ArrayList;
import javax.xml.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.OperationClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.synapse.MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
public class NTLMAuthorisation extends AbstractMediator {
/* private String soapAction;
private String soapEndpoint;
private String domain;
private String host;
private int port;
private String username;
private String password;
*/
public boolean mediate(MessageContext context) {
//Build NTLM Authentication Scheme
System.out.println("Class code executing...");
//AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, JCIFS_NTLMScheme.class);
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("XXXX");
auth.setPassword("P#XX");
auth.setDomain("XX");
auth.setHost("XXXX");
auth.setPort(80);
auth.setPreemptiveAuthentication(true);
ArrayList<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthPolicy.NTLM);
auth.setAuthSchemes(authPrefs);
System.out.println("auth.NTLM : "+authPrefs);
//Force Authentication - failures will get caught in the catch block
try {
//Build ServiceClient and set Authorization Options
ServiceClient serviceClient = new ServiceClient();
Options options = new Options();
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setAction("http://XXXXX/XXX/RetrieveMultiple");
options.setTo(new EndpointReference("http://XXXX/NZGP/XX/2011/XXX.svc/web"));
serviceClient.setOptions(options);
//Generate an OperationClient from the ServiceClient to execute the request
OperationClient opClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
//Have to translate MsgCtx from Synapse to Axis2
org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
axisMsgCtx.setEnvelope(context.getEnvelope());
opClient.addMessageContext(axisMsgCtx);
System.out.println("axisMsgCtx" + axisMsgCtx.toString());
//Send the request to the server
opClient.execute(true);
//Retrieve Result and replace mediation (synapse) context
SOAPEnvelope result = (SOAPEnvelope) opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope();
context.setEnvelope((org.apache.axiom.soap.SOAPEnvelope) result);
System.out.println("result : "+result);
} catch (AxisFault e) {
context.setProperty("ResponseCode", e.getFaultCodeElement().getText());
return false; //This stops the mediation flow, so I think it executes the fault sequence?
}
return true;
}
/*
public void setSoapAction(String _soapAction){
soapAction = _soapAction;
}
public String getSoapAction(){
return soapAction;
}
public void setSoapEndpoint(String _soapEndpoint){
soapEndpoint = _soapEndpoint;
}
public String getSoapEndpoint(){
return soapEndpoint;
}
public void setDomain(String _domain){
domain = _domain;
}
public String getDomain(){
return domain;
}
public void setHost(String _host){
host = _host;
}
public String getHost(){
return host;
}
public void setPort(int _port){
port = _port;
}
public int getPort(){
return port;
}
public void setUsername(String _username){
username = _username;
}
public String getUsername(){
return username;
}
public void setPassword(String _password){
password = _password;
}
public String getPassword(){
return password;
}*/
}

intermittent sending email java

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");//As discussed but does not work if the leave
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mail#domi.cl","paswwd");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail#domi.cl"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mail#domi.cl"));
message.setSubject("Resumen envio masivo");
message.setText(mensajeMail);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Below is the StackTrace:
Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
javax.faces.el.EvaluationException: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
The exception means that you are unable to connect to port 587 on server smtp.office365.com. Verify this using telnet:
telnet smtp.office365.com 587
Possible reasons for this to do not work from your location are:
Misconfigured proxy settings in Java
If it does not work and you are in a company network, then it's most likely the firewall which causes the problem. Also check if password and email is correct.
Maybe also it works with TLS. You should try it.
Please check the SMTP port number for your domain or try my code.
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
public class Mail {
String senderID;
String senderPassword;
String hostName;
int portNumber;
String attachmentPath;
String subject;
String body;
String cc;
String bcc;
// #=============================================================================================#
public String getBcc() {
return bcc;
}
// #=============================================================================================#
public void setBcc(String bcc) {
this.bcc = bcc;
}
// #=============================================================================================#
public String getCc() {
return cc;
}
// #=============================================================================================#
public void setCc(String cc) {
this.cc = cc;
}
// #=============================================================================================#
public String getBody() {
return body;
}
// #=============================================================================================#
public void setBody(String body) {
this.body = body;
}
// #=============================================================================================#
public String getSubject() {
return subject;
}
// #=============================================================================================#
public void setSubject(String subject) {
this.subject = subject;
}
// #=============================================================================================#
public String getSenderID() {
return senderID;
}
// #=============================================================================================#
public void setSenderID(String senderID) {
this.senderID = senderID;
}
public String getSenderPassword() {
return senderPassword;
}
// #=============================================================================================#
public void setSenderPassword(String senderPassword) {
this.senderPassword = senderPassword;
}
// #=============================================================================================#
public String getHostName() {
return hostName;
}
// #=============================================================================================#
public void setHostName(String hostName) {
this.hostName = hostName;
}
// #=============================================================================================#
public int getPortNumber() {
return portNumber;
}
// #=============================================================================================#
public void setPortNumber(int portNumber) {
this.portNumber = portNumber;
}
// #=============================================================================================#
public String getAttachmentPath() {
return attachmentPath;
}
// #=============================================================================================#
public void setAttachmentPath(String attachmentPath) {
this.attachmentPath = attachmentPath;
}
// #=============================================================================================#
// #=============================================================================================#
public void sendMail(String receiverId) {
try {
// this below commented line for the HTML body text
// MultiPartEmail htmlEmail = new HtmlEmail();
// OR
// HtmlEmail email = new HtmlEmail();
MultiPartEmail email = new MultiPartEmail();
// setting the port number
email.setSmtpPort(getPortNumber());
// authenticating the user
email.setAuthenticator(new DefaultAuthenticator(getSenderID(),
getSenderPassword()));
// email.setDebug(true);
email.setSSL(true);
// setting the host name
email.setHostName(getHostName());
// setting the rciever id
email.addTo(receiverId);
// check for user enterd cc or not
if (getCc() != null) {
// add the cc
email.addCc(getCc());
}
// check for user enterd bcc or not
if (getBcc() != null) {
// add the bcc
email.addBcc(getBcc());
}
// setting the sender id
email.setFrom(getSenderID());
// setting the subject of mail
email.setSubject(getSubject());
// setting message body
email.setMsg(getBody());
// email.setHtmlMsg("<h1>"+getBody()+"</h1>");
// checking for attachment attachment
if (getAttachmentPath() != null) {
// add the attachment
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(getAttachmentPath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
}
// send the email
email.send();
// System.out.println("Mail sent!");
} catch (Exception e) {
// System.out.println("Exception :: " + e);
// e.printStackTrace();
// gl.writeWarning("Error occured in SendMail.java of sendMailWithAttachment() ");
// gl.writeError(e);
}
}// sendmail()

Passing parameters to the class while passing the class as a `class literal`

I am trying to schedule a job using Quartz library. Below is the method belong to the class which schedules the job.
private void Reminder1()
{
String[] firstReminderTime = getFirstReminderTime().split(":");
Integer firstReminderHour = Integer.parseInt(firstReminderTime[0]);
Integer firstReminderMinute = Integer.parseInt(firstReminderTime[1]);
if(firstReminderHour==null || firstReminderMinute==null)
{
return;
}
JobDetail job = newJob(PJob.class).withIdentity("p1").build();
Trigger trigger = newTrigger()
.withIdentity(triggerKey("pTrigger1", "pTriggerGroup1"))
.withSchedule(dailyAtHourAndMinute(firstReminderHour, firstReminderMinute))
.startAt(new Date()).build();
try {
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
} catch (SchedulerException ex) {
ex.printStackTrace();
}
}
Below is the job class.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RemindeWorker.PJob;
import RemindeWorker.Listener.ReminderCommon;
import java.util.Properties;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
*
* #author Yohan
*/
public class PJob implements Job
{
private String host;
private String userName;
private String password;
private String firstReminderTime;
private String secondReminderTime;
public PJob(String host, String userName, String password, String firstReminderTime, String secondReminderTime)
{
setHost(host);
setUserName(userName);
setPassword(password);
setFirstReminderTime(firstReminderTime);
setSecondReminderTime(secondReminderTime);
}
#Override
public void execute(JobExecutionContext jec) throws JobExecutionException
{
String host=getHost();
final String user=getUserName();//change accordingly
final String password=getPassword();//change accordingly
String to="xxx#gmail.com";//change accordingly
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//Compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Subject");
message.setText("This is simple program of sending email using JavaMail API");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
} catch (MessagingException e) {e.printStackTrace();}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstReminderTime() {
return firstReminderTime;
}
public void setFirstReminderTime(String firstReminderTime) {
this.firstReminderTime = firstReminderTime;
}
public String getSecondReminderTime() {
return secondReminderTime;
}
public void setSecondReminderTime(String secondReminderTime) {
this.secondReminderTime = secondReminderTime;
}
}
However I have an issue. Please pay attention to the below
JobDetail job = newJob(PJob.class).withIdentity("p1").build();
Here we call the "class literal". But, I need to execute the constructor of the Job class, because it does accept the parameters. Passing parameters to this class is mandatory.
So my question is, since when passing the class literal, there is no way of passing the parameters, how I can pass them to the job class?
Create fake job which:
reads parameters from somewhere (properties, db etc)
creates real job using constructor with parameters
and schedule this fake job to quartz.

Liferay: How to specify CID for attachments (so they can be embeded (i.e images) in HTML content e-mails) in MailServiceUtil

Attachments need to be added like this
MailMessage.addAttachment(File file, [String fileName])
, but innerly it seems that fileName is only used for MimeBodyPart.setFileName()
I dont find anyway to use the
MimeBodyPart.setContentID("myID") or MimeBodyPart.setHeader("Content-ID", "myID");
feature, so I can use images embeded in mail with
<img src='CID:MyID'>
It seems MailEngine is in the portal jar so only for internal use, and I was not able to find a solution for MailServiceUtil. Does it mean I need to decode all Liferay high-level API stuff from scratch and use Java Mail API?
I don't think there's a way to do that with Liferay (at least not at version 6.2). But I made it work with standard Java approach. The following is pretty similar to Liferay interface.
public void send(TemplateEmailerMailMessage mailMessage) throws UnsupportedEncodingException {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailMessage.getFromEmail(), mailMessage.getFromName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailMessage.getTo()));
message.setSubject(mailMessage.getSubject());
if (mailMessage.isHtmlFormat()) {
message.setText(mailMessage.getBody(), "text/html");
} else {
message.setText(mailMessage.getBody());
}
// create container for attachments and body parts
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getBody(), "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// add attachments one by one
for (File file : mailMessage.getFileAttachments()) {
BodyPart messageAttachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentPart.setDataHandler(new DataHandler(source));
messageAttachmentPart.setFileName(file.getName());
// set Content-ID so it is recognized by <img src="cid: ... ">
messageAttachmentPart.setHeader("Content-ID", "<" + file.getName() + ">");
multipart.addBodyPart(messageAttachmentPart);
}
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
The message object
public class TemplateEmailerMailMessage {
private String fromEmail;
private String fromName;
private String to;
private String body;
private String subject;
private boolean htmlFormat;
private List<File> fileAttachments = new ArrayList<>();
public void addAttachment(File file) {
fileAttachments.add(file);
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public boolean isHtmlFormat() {
return htmlFormat;
}
public void setHtmlFormat(boolean htmlFormat) {
this.htmlFormat = htmlFormat;
}
public List<File> getFileAttachments() {
return fileAttachments;
}
public void setFileAttachments(List<File> fileAttachments) {
this.fileAttachments = fileAttachments;
}
public String getFromEmail() {
return fromEmail;
}
public void setFromEmail(String fromEmail) {
this.fromEmail = fromEmail;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public void setFrom(String fromEmail, String fromName) {
this.fromEmail = fromEmail;
this.fromName = fromName;
}
}

Categories

Resources