Does any one know how to send an email with the desired "from" name in Java ?
I have a code which sends the mail through gmail. Using the smtp settings of gmail, I am able to do that. But, using the same smtp settings, can I send an email from a non-existing mail ID ?
For example:
I have a code which sends an email from the existing username (say abc#gmail.com) and the receiver gets the email from abc#gmail.com . But , what I want is , can we send a mail from something like "a#def.com" ? So that, the user receives the mail from "a#def.com" ?
Is that possible ?
While the API may allow you to do that, your difficulty is going to be with the SMTP server's configuration. No sane SMTP server would allow you to control the "from" email address of email messages sent through that SMTP server - that's the first step of making your SMTP server an easy gateway for spammers. Proper SMTP servers (Google's included) will set the "from" email address to be identical to the one you logged in with.
You can set it explicitly. But again it depends on the SMTP server that accepts the FROM address. To my knowledge most of the SMTPs are configured to block the sender email ids that do not belong to its domain. If at all they are not configured so, the receiving mail clients may filter the message for not identifying the sender email id from the receiving server and set it as SPAM. This would also cause the SMTP domain being blocked by many other receiving domains.
Hence it is not suggested to be followed.
You need mail.jar and activation.jar. In my case i implemented using below method
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.Transport;
class ABC{
......
private void sendSimpleEmail(String to,String subject,String cc,String bcc,String message,HashMap mailMap)
{
String smtpHost=mailMap.get("mailhost").toString();
String smtpPort=mailMap.get("mailport").toString();
String authrequired=mailMap.get("auth").toString();
String from=mailMap.get("mailsendfrom").toString();
String SSLCheck=mailMap.get("sslconfig").toString();
/* For Authentication */
String password=mailMap.get("mailpwd").toString();
String fromUsername=mailMap.get("mailusername").toString();
/* For Authentication Ends*/
Properties props = new Properties();
props.put("mail.smtp.auth", authrequired);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session=Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(session);
try {
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
} catch (AddressException e) {
//Exception
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(message);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
}
}
.......
}
Related
I am currently receiving emails from Amazon SES, which I store on Amazon S3.
Then I have a program (written in Java) which retrieve emails from S3, parse them and do a specific action based on the recipient's name.
The issue
When an email is sent to 2 recipients (let's say A#mydomain.com and B#mydomain.com), Amazon SES receive 2 emails and store both of them in S3.
Both emails are identical (except for some custom headers set by my email client).
My Java program retrieve 2 emails from S3 but I can't determine for whom each email is intended, as both email addresses are present in the "TO" header of both emails.
What I found
Amazon SES store the MIME Message in S3
Based on the Internet Message Format RFC, MIME Message contains the full list of recipients, but not the actual recipient.
I guess this information is not part of the Mime Message, but part of the protocol.
It means that:
Amazon SES must know the recipient
Once the mail is stored in S3, this information is lost.
Based on the fact that this analyze is correct (which might not be), I wanted to use Amazon Lambda expressions to retrieve the protocols information and store them as metadata of the email in S3.
However, I cannot find a way to retrieve the protocols informations.
Any idea?
Does someone has any idea how to achieve this?
It would be nice if I could get the recipient's email address of each email from a Lambda expression, but I didn't found a lot of references about this.
Maybe my interpretation of how this work (the email protocol / process) is completely wrong and someone could give me some explanation! :D
Some code to go with it
I found some code displaying the information we have if we do a lambda function at the SES level, but I didn't find the information I needed there.
https://gist.github.com/gonfva/b249f76893165bf5a8d1
The S3Object also contains some Metadata but they don't seem to be useful.
Bellow is the Java code I use to retrieve emails from Amazon.
package fr.novapost.delivery.emailer.listener.amazon;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectId;
import org.apache.commons.mail.util.MimeMessageParser;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
// Fill these variables with the proper values.
String objectName = "";
String bucketName = "";
String accessKey = "";
String secretAccessKey = "";
BasicAWSCredentials awsCred = new BasicAWSCredentials(accessKey, secretAccessKey);
AWSCredentialsProvider credentialProvider = new AWSStaticCredentialsProvider(awsCred);
// Create S3 client
AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialProvider).withRegion(Regions.EU_WEST_1).build();
// Retrieve object from S3
GetObjectRequest request = new GetObjectRequest(new S3ObjectId(bucketName, objectName));
S3Object s3Object = amazonS3.getObject(request);
// Get content of the object (which is the MimeMessage) and create a MimeMessage from it.
Session s = Session.getInstance(new Properties());
try {
MimeMessage mail = new MimeMessage(s, s3Object.getObjectContent());
// Parse the mime message thanks to the org.apache.commons.mail.util.MimeMessageParser class.
MimeMessageParser mimeParser = new MimeMessageParser(mail);
mimeParser.parse();
// Get the recipient's list.
// It contains ALL the recipients.
// I want to know for which specific recipient of this list this email was intended.
List<Address> addresses = mimeParser.getTo();
for (Address address : addresses) {
System.out.println("recipient: " + address.toString());
}
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The recipients as they may be suggested by To: and Cc: mail headers are irrelevant, as those are not actually used for delivery (and in the case of BCC, the recipient should definitely not appear there).
You should find that SES adds the actual envelope recipient (which is what you are looking for) in the first Received: header from the top.
Return-Path: <...>
Received: from x-x-x (x-x-x [x.x.x.x])
by inbound-smtp.us-east-1.amazonaws.com with SMTP id xxxxxxxxxxxxxxxxxxxx
for the-actual-recipient-is-this-address#example.com;
Sat, 15 Jul 2017 05:07:18 +0000 (UTC)
X-SES-Spam-Verdict: PASS
X-SES-Virus-Verdict: PASS
Received: headers are prepended as mail is processed, so you they become less trustworthy as you work down -- but the top one comes from SES itself.
I am stuck behind a corporate firewall that won't let me send email via conventional means such as Java Mail API or Apache Commons Email, even to other people inside the organization(which is all I want anyways). But my Outlook 2010 obviously can send these emails. I was wondering if there is a way to automate Outlook 2010 via Java code so that Outlook can send the emails ? I know stuff like "mailto" can be used pop-up the default Outlook send dialog with pre-populated info, but I am looking for a way to have the send operation happen behind the scenes. Thanks for any info.
You can send emails through outlook with javamail use the configurations described on Outlook's official site.
Here is small demo code
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public static void main(String[] args) {
final String username = "your email"; // like yourname#outlook.com
final String password = "*********"; // password here
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver mail")); // like inzi769#gmail.com
message.setSubject("Test");
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
.
Note: I tested this with Javamail API 1.5.6
I don't think there's any way to do what you want using Outlook.
Presumably your mail server is also behind the corporate firewall. If you're using Outlook for your client, you're probably using Exchange for your server. Exchange can be configured to support the standard SMTP protocol for sending mail, which would allow use of JavaMail. If you can't configure your Exchange server to support SMTP, you still might be able to use Exchange Web Services. If that doesn't work, you might need to use one of the JavaMail Third Party Products that supports the Microsoft proprietary mail protocol.
Process p = Runtime.getRuntime().exec("cmd /C start outlook ");
I try to run a small Programm that sends an generic Email to my Account
But I get an Exception:
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 553 We do not relay non-local mail, sorry.
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1873)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:54)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 553 We do not relay non-local mail, sorry.
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1724)
... 4 more
This is my Code
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "Basti-V#web.de";
// Sender's email ID needs to be mentioned
String from = "Basti-V#web.de";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Im using the XAMPP Control Panel to run a Mercury Server. The Ports are 25,79,105,106,110,143 and 2224. Im new to this so maybe someone can push me in the right direction.
You must uncheck "Do not permit SMTP relaying of non-local mail" option.
See the link: uncheck option
Please check below two things.
1).where the host mail server is running. If it is running in local machine then set the host address as 0.0.0.0
2.If it is external mail server, check the mail credentials like username, password, host.
I think 553 is "denied error" from server, that means you have not provided correct credential .
I am sending e email using an SMTP error . I am getting Authentication unsuccessful. The username and password are correct. Am I doing something wrong.
The error logs are
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender{
public static void main(String args[]) {
String to = "ssss#xxx.om"; // sender email
String from = "dddd#xxx.com"; // receiver email
String host = "dkdkdd.xxx.com"; // mail server host
String login="dkkdkd";
String pass="dkkdkd";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.user", login);
properties.setProperty("mail.smtp.password", pass);
properties.setProperty("mail.smtps.ssl.enable", "true");
// properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties); // default session
try {
MimeMessage message = new MimeMessage(session); // email message
message.setFrom(new InternetAddress(from)); // setting header fields
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail from Java Program"); // subject line
// actual mail body
message.setText("You can send mail from Java program by using");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, login, pass);
Transport.send(message);
System.out.println("Email Sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
The error is
DEBUG SMTP: AUTH NTLM failed
Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Had the same issue. It's an MS Exchange error that you receive. You are probably not allowed to use your email to send an email via a relay. The administrator of the Exchange server needs to give the rights to do that.
It has nothing to do with a configuration problem on the Java side.
It looks like the problem in how you do the session part...
try doing this:
private Properties emailPorperties;
...
...
emailPorperties = new Properties();
emailPorperties.put("mail.smtp.host", "your host");
emailPorperties.put("mail.smtp.socketFactory.port", "your port");
emailPorperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
emailPorperties.put("mail.smtp.auth", "true");
emailPorperties.put("mail.smtp.port", "your port");
emailPorperties.put("mail.smtp.ssl.enable", "true");
emailSession = Session.getInstance(emailPorperties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("Authenticating");
return new PasswordAuthentication(USER_NAME, PASSWORD);
}
});
Hello i've got the same issue in the past.
So to solve it i have to connect on the webmail of my outlook or exchage and i noticed that these connexions were stopped by the server so inside i confirm that these transactions was mine.
So u have also to do it usually every 2 month in my case.
The problem is not in the code. The problem occurs because something is wrong with the configuration of the mailboxes I believe.
Same issue resolve by enabling IMAP of the sender email account in Exchange Control Panel (ECP) of outlook mail admin.
Go to your Microsoft admin account and turn off the multi-factor authentication.
By default it is enabled. Once you disable the multi-factor authentication then it works fine for me.
I had a similar issue and in my case, the issue was 'outlook password got expired'.
As I had it logged in default I did not have any issue while logging in to my mail.
I tried logging in to incognito mode and see if my logging asked for an additional layer for logging like multi-factor auth, And when logged in from the incognito tab it asked to change the password with a popup stating 'password got expired'.
I then updated the new password and it started to work fine !!
I'm trying to work with the below code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*; // important
import javax.mail.event.*; // important
import java.net.*;
import java.util.*;
public class servletmail extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
try {
Properties props=new Properties();
props.put("mail.smtp.host","localhost"); // 'localhost' for testing
Session session1 = Session.getDefaultInstance(props,null);
String s1 = request.getParameter("text1"); //sender (from)
String s2 = request.getParameter("text2");
String s3 = request.getParameter("text3");
String s4 = request.getParameter("area1");
Message message =new MimeMessage(session1);
message.setFrom(new InternetAddress(s1));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(s2,false));
message.setSubject(s3);
message.setText(s4);
Transport.send(message);
out.println("mail has been sent");
} catch(Exception ex) {
System.out.println("ERROR....."+ex);
}
}
}
I'm using mail.jar and activation.jar. But I can't understand how I should configure it with a mail server. Which mail server should I use? Will I be able to send an email using above code? What are the requirements a mail server? How should I configure it?
To start, you need a SMTP server. It's required to be able to send emails. The same way as you need a HTTP server to be able to serve a website. You apparently already have a HTTP server (with a servletcontainer), but you don't have a SMTP server configured yet.
You can make use of the SMTP server associated with your own existing email account, such as the one from your ISP or public mailboxes like Gmail, Yahoo, etc. You can find SMTP connection details in their documentation. You usually just need to know the hostname and the port number. The username/password are just the same as those of your email account.
The hostname and port number should then be set as SMTP properties for JavaMail:
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.smtp.host", "smtp.example.com"); // smtp.gmail.com?
properties.put("mail.smtp.port", "25");
The username/password should be used in a Authenticator as follows:
properties.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourusername", "yourpassword");
}
};
Then you can get the mail session as follows:
Session session = Session.getDefaultInstance(properties, authenticator);
With the account of your ISP or public mailboxes, you're however restricted to using your own address in the From field of the email and usually also in the amount of emails you're allowed to send at certain intervals. If you'd like to get around this, then you need to install your own SMTP server, for example Apache James, which is Java based, or Microsoft Exchange and so on.
After all, I suggest you to get yourself through a JavaMail tutorial so that you get a better understanding.