I want to setup my mail server in a way so that if someone sends email to user#example.com it'll be directed to user's inbox. This is not mail box. Rather its a chat platform. So communication should be real time. The workflow is,
Someone sends an email to user#example.com.
user gets a chat window with that message.
I can solve it by writing a program that polls the mail server each min and check for new messages. If found it just send a chat message. But that not real-time.
Another option could be adding some sort of plugin to the mail server that does the work. I haven't setup any mail server yet. I'll setup only that mail server that helps me to do this.
I am using Python, PHP. So any solution using those two language is welcomed. If all else fails I guess I have to write plugin in C.
Lamson could work, it's written in Python. It sits in front of your SMTP server and filters out the emails you define in it's routes file. The main rationale appears to be ease of developer use, and it's designed to be integrated into other software.
http://lamsonproject.org/
That's how you can do it:
1) Set up your DNS so that a MX record for the domain points to your server.
2) Configure a postfix virtual alias /etc/postfix/virtual:
#example.com django-mail-in
3) and /etc/aliases:
django-mail-in: "|/usr/local/bin/mta2django.py http://127.0.0.1:8000/mail-inbound"
4) The /usr/local/bin/mta2django.py is called by postscript and sends the mail to the mail-inbound django view. This mta2django.py should work:
#!/usr/bin/python
import sys, urllib
import os
def post_message(url, recipient, message_txt):
""" post an email message to the given url
"""
if not url:
print "Invalid url."
print "usage: mta2django.py url <recipient>"
sys.exit(64)
data = {'mail': message_txt}
if recipient and len(recipient) > 0:
data ['recipient'] = recipient
try:
result = urllib.urlopen(url, urllib.urlencode(data)).read()
except (IOError,EOFError),e:
print "error: could not connect to server",e
sys.exit(73)
try:
exitcode, errormsg = result.split(':')
if exitcode != '0':
print 'Error %s: %s' % (exitcode, errormsg)
sys.exit(int(exitcode))
except ValueError:
print 'Unknown error.'
sys.exit(69)
sys.exit(0)
if __name__ == '__main__':
# This gets called by the MTA when a new message arrives.
# The mail message file gets passed in on the stdin
# Get the raw mail
message_txt = sys.stdin.read()
url = ''
if len(sys.argv)>1:
url = sys.argv[1]
recipient = ''
# If mta2django is executed as external command by the MTA, the
# environment variable ORIGINAL_RECIPIENT contains the entire
# recipient address, before any address rewriting or aliasing
recipient = os.environ.get('ORIGINAL_RECIPIENT')
if len(sys.argv)>2:
recipient = sys.argv[2]
post_message(url, recipient, message_txt)
5) Write a django view /mail-inbound which receives the mail and does the things you need it to do. In the request you have:
mail - the full email message
recipient - the original recipient (useful when you do not catch a specific email address but the whole domain / subdomain)
You can parse the email using the python email module:
import email
msg = email.message_from_string(request.get('mail'))
As I'm no postfix expert, I'm not sure if editing /etc/postfix/virtual and /etc/aliases is sufficient. Please consult the postfix documentation for details.
Related
I'm looking for a way to capture and manage email data using PHP. Basically, what I want to do is capture all the data in an email and then manipulate this data to my specification.
For example, say, I send an email containing a .zip file attachment to myemail#myproject.com, I want to be able to:
Get the attachment and place it in a specific folder on my site
Get the text content of the email
Get the subject of the email
Get the sender's info i.e. email address
Anyone know how I can get this done efficiently with PHP. I'm using LAMP by the way.
Thanks.
Start with PEAR Mail_mimeDecode. What you are looking to do is ambitious but can be done.
Basically what you will be doing is:
Instructing your MTA to deliver mail from an address to a pipe into your PHP script. Postfix and Sendmail can handle this with an alias like:
myemail: "|/path/to/your/parsingscript.php"
Parsing out the parts of the MIME email message
Locating and storing attachments after decoding them from base64 (or other encoding)
Parsing the headers.
Your PHP script will likely read the email message from STDIN and then pass the string to mimeDecode, which creates an object containing all the MIME parts.
Assuming your message was received into $str from STDIN, something like this gets you started:
$mime = Mail_mimeDecode::decode(array('include_bodies'=>TRUE, 'decode_headers'=>TRUE, 'decode_bodies'=>TRUE, 'input'=>$str));
// get the recipient To address:
$to = $mime->headers['to'];
I'm using SwiftMailer for PHP from swiftmailer.org
Everything works well but I wonder if there is a way to add the sent message into the sent folder from the mail account that SwiftMailer is sending from?
That's all, have a nice day.
According to the developer, swiftmailer cannot copy to Sent folder because it is a mail sender and not mailbox manager.
As mentioned on the github page:
Swiftmailer is a library to send emails, not to manage mailboxes. So, this is indeed out of the scope of Swiftmailer.
However, someone from php.net posted a solution that might work for you:
Use SwiftMailer to send the message via PHP.
$message = Swift_Message::newInstance("Subject goes here");
// (then add from, to, body, attachments etc)
$result = $mailer->send($message);
When you construct the message in step 1) above save it to a variable as follows:
$msg = $message->toString();
// (this creates the full MIME message required for imap_append()!!
// After this you can call imap_append like this:
imap_append($imap_conn,$mail_box,$msg."\r\n","\\Seen");
I've had similar problem and Sutandiono's answer got me into right direction. However because of completeness and as I had additional problem connecting to an Exchange 2007 server, I wanted to provide a complete snippet for storing message to Sent folder on IMAP:
$msg = $message->toString();
// $message is instance of Swift_Message from SwiftMailer
$stream = imap_open("{mail.XXXXX.org/imap/ssl/novalidate-cert}", "username", "password", null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
// connect to IMAP SSL (port 993) without Kerberos and no certificate validation
imap_append($stream,"{mail.XXXXX.org/imap/ssl/novalidate-cert}Sent Items",$msg."\r\n","\\Seen");
// Saves message to Sent folder and marks it as read
imap_close($stream);
// Close connection to the server when you're done
Replace server hostname, username and password with your own information.
I'm trying to handle bounced message and send to a responsible System Administrator.
I use CakePHP Email Component to send the message. On server side, I use postfix to transport the message.
function sendAsEmail($data) {
$Email->sendAs = 'html';
$Email->from = $user['Sender']['username'] . '#example.com';
$Email->return = Configure::read('App.systemAdminEmail');
$Email->bcc = array($data['Message']['recipient_text']);
$content = 'Some content';
$Email->send($content);
}
As you can see above, I set the $Email->return to sysadmin's email which it will send all the bounced message.
On postfix configuration, I tried creating a bounce.cf template and set bounce_template_file. http://www.howtoforge.com/configure-custom-postfix-bounce-messages
How do I get the bounced message and send it to System Administrator?
I think what you'll need to do is to use an SMTP (or I suppose POP3) connector for PHP. Then you'll basically have to create your own PHP email client that will login to the server, ask for the messages that have been bounced, and parse them appropriately.
I would think there would be a CakePHP component for this, but I can't find one.
I would recommend that you use an Envelope Header in your email. Otherwise you'll be stuck trying to parse the recipient server bounce, and those are very very inconsistent. If you use the VERP (variable envelope return protocol?) header, you can encode a unique hash into the email address which should be really easy to parse out in your PHPEmailClient.
More info on VERP: http://en.wikipedia.org/wiki/Variable_envelope_return_path
Cake-specific VERP stuff: http://www.mainelydesign.com/blog/view/setting-envelope-from-header-cakephp-email-component
I also highly recommend that you look into using SwiftMailer. It has a lot of plugins; you might find a base PHP SMTP client that you can easily modify to do what you need. http://swiftmailer.org/
I'm wondering how i would go about making the following application:
a user signs up, say with the username "johny-jones".
Lets say for example that my domain is www.example.com
if anyone emails johny-jones#example.com this email is redirected to johny-jones REAL email address
The simplest option is to tell your smtp server to forward all ingoing mails to an external program (your php script). For example, for qmail this will be like | php myphpscript.php in .qmail file. Your script will read email from stdin and resend it to the real address.
You're basically describing a mail transfer agent AKA mail server. So all you need to do is a server to run it on, the required MX DNS records, and an API that allows you to configure forward addresses. Look through the documentation of the servers
listed here to see which ones offer the latter.
Just pipe all orphan email (specific to that domain) to ur PHP script and use something like this to extract the email content:
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
then extract the "to" field and if it belongs to a user .. forward the email to him.If you have cPanel .. this is even easier. goto mail > default address > set default address and instead of putting an email address there put something like this
"|php -q /home/whatever/public_html/pipe.php" .. ofcourse without the quotes
I'm trying to sends mails in PHP. The code I used for sending a mail in CakePHP is given below. I get the message 'Simple Email Sent' in my web page but the mail is not delivered to my inbox. Am I missing something?
The values in the to, subject and link fields are set with the values entered in the user interface.
$this->set('to',$this->params['form']['to']);
$this->set('subject',$this->params['form']['subject']);
$this->set('link',$this->params['form']['link']);
$this->Email->to = to;
$this->Email->subject = subject;
$this->Email->from = 'someperson#somedomain.com';
$this->Email->delivery= 'mail';
$this->Email->sendAs='text';
$this->Email->template = 'simple_message';
//$this->Email->send(link);
if ( $this->Email->send(link) ) {
$this->Session->setFlash('Simple email sent');
} else {
$this->Session->setFlash('Simple email not sent');
}
On a Linux system, you'll probably have a sendmail script installed already, and PHP will use that. If this is what you have and it's not working, then I'd look for mail configuration problems in your Linux system itself.
On a Windows system, you'll need to configure the SMTP server you want PHP to send mail to. The normal way to do this is in php.ini. The instructions for this are here.
Unless you have set Email->delivery this should be the same for CakePHP - it should default to whatever PHP uses.
Note: If you are using your own Linux install, it could just be that your ISP is blocking port 25, which your mail server is using. In that case you'll need to configure linux to route email to your ISP's email server. Maybe this will help?
Since when is 'to' (line 4) a valid destination email address?
You need to use variable syntax for setting to 'to' line, and the 'subject' line. Those lines should read
$this->Email->to = to;
$this->Email->subject = subject;
Also, I believe there is an attribute in the Email component called error (I cannot find it in the documentation currently) that will help you debug. This may not be totally correct; I use the Email component with SMTP, and there is an attribute that gets set by the Email component called smtpError. I believe there is one called error that you can use to check for an error -- it should contain code that will tell you where your problem lies.
In case that's an incorrect statement, you can always do a var_dump( $this->Email ); after you try to send an email. That will dump the entire contents of the object, so you can see if you have set attributes correctly, and it should help you find out what the error attribute is named.